How do I copy or clone a LinkedList-implemented Queue in Java?

Razer picture Razer · Apr 10, 2014 · Viewed 25.8k times · Source

I have a Queue q1, that is implemented as a LinkedList, and I want to define a Queue q2, that is a separate, but identical identical instance of Queue q1.

How do I do that since Queue does not implement Cloneable?

Answer

Kayaman picture Kayaman · Apr 10, 2014

In a one liner:

new LinkedList<>(myQueue);

Since Queue extends Collection, and collections have a constructor that takes another Collection, this is a quick way to do a shallow clone.

Substitute LinkedList with your own Queue implementation if you wish.

Also, read the javadocs. They have all the answers.