我研究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)