I wish to create a Queue (or Stack) in java using all the elements from an array. Is there some 'nice' way of doing this, i.e in one line without a loop over the array?
To convert array-based data into Collection based we can use java. util. Arrays class. This class provides a static method asList(T… a) that converts the array into a Collection.
You can represent queues in the form of an array using pointers: front and rear.
In array implementation of queue, we create an array queue of size n with two variables top and end. Now, initially, the array is empty i.e. both top and end are at 0 indexes of the array. And as elements are added to the queue (insertion) the end variable's value is increased.
This should work. yourArray is the input array. Substitute Object for whatever data type you're dealing with.
Queue<Object> queue = new LinkedList<>(Arrays.asList(yourArray));
For stacks, you should create a vector object, because stack extends Vector class.
Stack<Object> stack = (Stack<Object>) new Vector(Arrays.asList(theArray));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With