如何制作List类型的ArrayList对象的副本?

mas*_*san 7 java clone copy

我研究Java是通过值传递对象引用,并且为了制作对象的本地副本,我可以做clone()或copy-constructor.我还查看了深/浅副本以及stackoverflow上的几个帖子.

现在我看一下例子:

List<String> list = new ArrayList<String>();
String one = "one"
list.add(one);
Run Code Online (Sandbox Code Playgroud)

我读过的文章很少提到ArrayList实现了cloneable,但是如果type是List not ArrayList并且没有实现cloneable,那么它并没有真正说明如何制作"list"的本地副本.

如果"list"是ArrayList的类型,我可以调用clone().

ArrayList<String> list = new ArrayList<String();
list.clone();
Run Code Online (Sandbox Code Playgroud)

但如果type是List,我不能.

我应该只使用下面的复制构造函数来制作本地副本吗?复制"列表"的最佳方法是什么?

List<String> tmpList = new ArrayList<String>(list);
Run Code Online (Sandbox Code Playgroud)

Joh*_*int 5

将列表传递给构造函数可能是最好的方法.构造函数调用本身将在后台使用System.arraycopy.因此,它将有效地从通过构造函数传递的列表中分离本地副本.