如何使ArrayList对象的副本是List的类型? [英] How to make a copy of ArrayList object which is type of List?

查看:434
本文介绍了如何使ArrayList对象的副本是List的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我学习Java是通过值传递对象引用,为了做一个对象的本地副本,我可以做clone()或copy-constructor。我也看了深/浅拷贝以及stackoverflow上的几个帖子。



现在我看一个例子:

  List< String> list = new ArrayList< String>(); 
String one =one
list.add(one);

很少有文章我只读到提到ArrayList实现了可克隆但并不真正说如何做一个本地副本



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

  ArrayList< String> list = new ArrayList< String(); 
list.clone();

但如果类型是List,我不能。



我应该使用下面的复制构造函数来进行本地复制吗?

 列表< String> tmpList = new ArrayList< String>(list); 


解决方案

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


I studied Java is pass object reference 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 post on stackoverflow.

Now I am looking at example:

List<String> list = new ArrayList<String>();
String one = "one"
list.add(one);

Few articles I read only mentions that ArrayList implements cloneable but does not really say how to make a local copy of "list" if type is List not ArrayList which does not implements cloneable.

I can call clone() if "list" is type of ArrayList.

ArrayList<String> list = new ArrayList<String();
list.clone();

But if type is List, I cannot.

Should I just use copy constructor like below to make local copy? What is the best way to make a copy of "list"?

List<String> tmpList = new ArrayList<String>(list);

解决方案

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.

这篇关于如何使ArrayList对象的副本是List的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆