如何在 Java 中复制或克隆 LinkedList 实现的队列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22982157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I copy or clone a LinkedList-implemented Queue in Java?
提问by Razer
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,它是作为 a 实现的LinkedList
,我想定义一个Queue
q2,它是Queue
q1 的一个单独但完全相同的实例。
How do I do that since Queue
does not implement Cloneable
?
既然Queue
没有实现,我该怎么做Cloneable
?
采纳答案by Kayaman
In a one liner:
在一个班轮中:
new LinkedList<>(myQueue);
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.
如果您愿意LinkedList
,可以用您自己的Queue
实现代替。
Also, read the javadocs. They have all the answers.
另外,阅读javadocs。他们有所有的答案。
回答by Evgeniy Dorofeev
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);
}
回答by mherbert
you can use an iterator :
您可以使用迭代器:
Iterator<Integer> it = q1.iterator();
while(it.hasNext()) {
q2.add(it.next());
}