Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Array to Queue

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?

like image 201
TeeMee123 Avatar asked Jul 30 '17 01:07

TeeMee123


People also ask

How do I convert an array to a collection in Java?

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.

Can you have an array of queues?

You can represent queues in the form of an array using pointers: front and rear.

What is array implementation queue?

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.


2 Answers

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));
like image 100
Rahul Chowdhury Avatar answered Oct 24 '22 23:10

Rahul Chowdhury


For stacks, you should create a vector object, because stack extends Vector class.

Stack<Object> stack = (Stack<Object>) new Vector(Arrays.asList(theArray));
like image 33
Oguz Avatar answered Oct 24 '22 23:10

Oguz