来自 this SO-question, answers and comments我知道结果是
ArrayList<Object> listClone = new ArrayList<Object>(list);
与
相比,在幕后做了额外的一步@SuppressWarnings("unchecked")
ArrayList<Object> listClone = (ArrayList<Object>)list.clone();
但结果是一样的。那么,为什么我们有 Clone 方法
时还要有 Copy Constructor
?
注意:这个问题主要针对ArrayList
,因为我知道它有一个Copy Constructor
和一个Clone Method
。如果有任何 Java 对象具有它们中的任何一个,但不是两者,那么我就不知道了。不过,我的问题还是针对 ArrayList
的情况。
那么,这样做的目的是什么?在哪种情况下,您更愿意使用 ArrayList 的 Copy Constructor
而不是其 Clone 方法
?
PS:如果谁有Java#ArrayList
的Copy Constructor
和Clone Method
的确切代码进行比较,那会很棒。
最佳答案
So, what is the purpose of it?
查看拷贝构造函数的签名:
ArrayList(Collection<? extends E> c)
它从任何集合构造一个列表;例如一个 LinkedList
,任何类型的 Set
,等等。
相比之下,您只能从另一个 ArrayList
clone()
一个 ArrayList
。
现在毫无疑问,clone()
总体上存在“问题”。但是(至少)对于标准的非并发集合类,克隆的工作方式与复制构造函数一样好......它完成工作的模数;往上看。对于这些类,clone()
方法被定义为返回浅拷贝;请参阅相应的类 javadoc。
If anyone has the exact code of both the Copy Constructor and the Clone Method of the Java#ArrayList for comparison, that would be great.
Google 是您的 friend 。 Google “java.util.ArrayList”源代码
。
(我更喜欢 Grepcode 站点。它有多个版本的代码,以及用于导航代码、包层次结构、类层次结构,甚至定义/使用关系的漂亮 UI。)
关于java - 存在克隆方法时复制构造函数的用途?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25058351/