12

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?

TeeMee123
  • 151
  • 1
  • 1
  • 10

2 Answers2

24

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));
Rahul Chowdhury
  • 641
  • 1
  • 7
  • 16
3

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

Stack<Object> stack = (Stack<Object>) new Vector(Arrays.asList(theArray));
Oguz
  • 1,867
  • 1
  • 17
  • 24