简体   繁体   English

如何在 Java 中复制或克隆 LinkedList 实现的队列?

[英]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.我有一个Queue q1,它是作为LinkedList实现的,我想定义一个Queue q2,它是Queue q1 的一个单独但完全相同的实例。

How do I do that since Queue does not implement Cloneable ?由于Queue没有实现Cloneable ,我该怎么做?

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.由于Queue extends Collection ,并且集合有一个接受另一个Collection的构造函数,因此这是进行浅层克隆的快速方法。

Substitute LinkedList with your own Queue implementation if you wish.如果您愿意,可以用您自己的Queue实现替换LinkedList

Also, read the javadocs.另外,阅读javadocs。 They have all the answers.他们有所有的答案。

you can use an iterator :您可以使用迭代器:

Iterator<Integer> it = q1.iterator();
while(it.hasNext())  {
   q2.add(it.next());
}

If q1 is one of JCF implementations of Queue like ArrayQueue etc are Cloneable you can use如果 q1 是 Queue 的 JCF 实现之一,如 ArrayQueue 等是可克隆的,您可以使用

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

otherwise除此以外

    Queue q2 = q1.getClass().newInstance();
    for(Object e : q1) {
        q2.add(e);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM