Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 269
Razer Avatar asked Apr 10 '14 08:04

Razer


Video Answer


3 Answers

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.

like image 99
Kayaman Avatar answered Oct 11 '22 04:10

Kayaman


you can use an iterator :

Iterator<Integer> it = q1.iterator();
while(it.hasNext())  {
   q2.add(it.next());
}
like image 5
mherbert Avatar answered Oct 11 '22 04:10

mherbert


If q1 is one of JCF implementations of Queue like ArrayQueue etc are Cloneable you can use

    Queue q2 = ((Cloneable)q1).clone();

otherwise

    Queue q2 = q1.getClass().newInstance();
    for(Object e : q1) {
        q2.add(e);
    }
like image 3
Evgeniy Dorofeev Avatar answered Oct 11 '22 03:10

Evgeniy Dorofeev