1

Is there a static factory method for creating a queue in Java?

I found several methods for creating Lists. For example:

Arrays.asList(T... a); 

or

List.of(E... elements) 

But can't find a convenient way to do the same for queues (or dequeues). The only solution I found is:

new LinkedList<>(Arrays.asList(elements))
Amal K
  • 4,359
  • 2
  • 22
  • 44
Volodya Lombrozo
  • 2,325
  • 2
  • 16
  • 34
  • That seems like a fine solution. – khelwood Jun 15 '21 at 09:15
  • there are no direct static methods? – Volodya Lombrozo Jun 15 '21 at 09:17
  • No there are no available static methods in the jdk – Lino Jun 15 '21 at 09:19
  • In queue, you cannot do a random access for the elements. So you cannot have a static utility for initialization. Well you can always use a stream() to do that elegantly – bradley101 Jun 15 '21 at 09:43
  • @Shantanu What has random access got to do with the existence of a static factory method? – khelwood Jun 15 '21 at 14:51
  • 1
    When you need a queue or deque, you should first consider `ArrayDeque` rather than `LinkedList`. But besides that, you already named a working approach. Alternatively, you can always use `Collections.addAll(collection, elements);` – Holger Jun 16 '21 at 08:20
  • Thank you for you suggestion. But I don't understand why ```ArrayDequeue``` is the preferred option? – Volodya Lombrozo Jun 16 '21 at 08:23
  • 1
    That has been discussed in [When to use LinkedList over ArrayList in Java?](https://stackoverflow.com/q/322715/2711488). The array based collections are more efficient in most use cases. There’s already a difference between `new LinkedList<>(Arrays.asList(elements))` and `new ArrayDeque<>(Arrays.asList(elements))`. [This tweet](https://twitter.com/joshbloch/status/583813919019573248) from the author of `LinkedList` is also illustrative. – Holger Jun 16 '21 at 08:55

0 Answers0