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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:37:45  来源:igfitidea点击:

ArrayList shallow copy iterate or clone()

java

提问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 Michael Borgwardt

Instead of iterating manually you can use the copy constructor.

您可以使用复制构造函数代替手动迭代。

As for the speed difference between that and using clone():

至于它和 using 之间的速度差异clone()

  1. It doesn't matter
  2. Most likely there is none
  3. Do a benchmark for your specific system configuration and use case
  1. 没关系
  2. 很可能没有
  3. 为您的特定系统配置和用例做一个基准测试

回答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 ??

这有什么问题吗??