如何制作 List 类型的 ArrayList 对象的副本?
我研究过 Java 按值传递对象引用,为了制作对象的本地副本,我可以使用 clone() 或复制构造函数.我还查看了深/浅拷贝以及 Stack Overflow 上的几篇文章.
I studied that Java passes object references by value, and in order to make a local copy of an object I can either do clone() or copy-constructor. I also looked at deep/shallow copy as well as several posts on Stack Overflow.
我在看这个例子:
List<String> list = new ArrayList<String>();
String one = "one"
list.add(one);
我读过的只有几篇文章提到 ArrayList 实现了可克隆,但并没有真正说明如何制作list"的本地副本.如果类型是List,而不是ArrayList,不实现cloneable.
Only a few articles I read mention that ArrayList implements cloneable, but does not really say how to make a local copy of "list" if the type is List, not ArrayList which does not implement cloneable.
我可以调用 clone() 如果list";是 ArrayList 的类型.
I can call clone() if "list" is type of ArrayList.
ArrayList<String> list = new ArrayList<String>();
list.clone();
但如果 type 是 List,我不能.
But if type is List, I cannot.
我应该只使用下面的复制构造函数来制作本地副本吗?制作list"副本的最佳方法是什么?
Should I just use the copy constructor like below to make a local copy? What is the best way to make a copy of "list"?
List<String> tmpList = new ArrayList<String>(list);
推荐答案
将列表传递给构造函数可能是最好的方法.构造函数调用本身将在幕后使用 System.arraycopy.因此它将有效地将本地副本从通过构造函数传入的列表中分离出来.
Passing the list into the constructor is probably the best way to go. The constructor invocation itself will use, behind the scenes, System.arraycopy. So it will effectively detach the local copy from the list passed in through the constructor.
相关文章