Java ArrayList 浅拷贝 iterate 或 clone()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2592985/
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
ArrayList shallow copy iterate or clone()
提问by tech20nn
I need a shallow copy of an java ArrayList
, should I use clone()
or iterate over original list and copy elements in to new arrayList, which is faster ?
我需要一个 java 的浅拷贝ArrayList
,我应该使用clone()
还是迭代原始列表并将元素复制到新的 arrayList 中,哪个更快?
采纳答案by Bozho
Use clone()
, or use the copy-constructor.
使用clone()
,或使用复制构造函数。
The copy-constructor makes additional transformation from the passed collection to array, while the clone()
method uses the internal array directly.
复制构造函数从传递的集合到数组进行额外的转换,而该clone()
方法直接使用内部数组。
Have in mind that clone()
returns Object
, so you will have to cast to List
.
请记住,clone()
返回Object
,因此您将不得不强制转换为List
。
回答by Bart Kiers
No need to iterate:
无需迭代:
List original = ...
List shallowCopy = new ArrayList(original);
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29
回答by Michael Borgwardt
Instead of iterating manually you can use the copy constructor.
您可以使用复制构造函数代替手动迭代。
As for the speed difference between that and using clone()
:
至于它和 using 之间的速度差异clone()
:
- It doesn't matter
- Most likely there is none
- Do a benchmark for your specific system configuration and use case
- 没关系
- 很可能没有
- 为您的特定系统配置和用例做一个基准测试
回答by Gaurav Kaushik
the question says shallowcopy not deepcopy.Copying directly reference from one arraylist reference to another will also work right.Deep copy includes copy individual element in arraylist.
问题是浅拷贝而不是深拷贝。将一个数组列表中的直接引用复制到另一个数组列表中也可以正常工作。深拷贝包括复制数组列表中的单个元素。
ArrayList<Integer> list=new ArrayList<Integer>();
list.add(3);
ArrayList<Integer> list1=list; //shallow copy...
Is there any problem in this ??
这有什么问题吗??