0

我有一个关于 Java 中 ArrayList 的 clone() 方法的问题。

ArrayList<HeavyOjbect> original = new ArrayList<HeavyOjbect>();
original.add(new HeavyOjbect(0));
original.add(new HeavyOjbect(1));
original.add(new HeavyOjbect(2));
ArrayList<Integer> copy = original;
copy.remove(0);

原始 -> [HeavyOjbect1,HeavyOjbect2]

复制-> [HeavyOjbect1,HeavyOjbect2]

现在使用 clone() 方法

ArrayList<HeavyOjbect> original = new ArrayList<HeavyOjbect>();
original.add(new HeavyOjbect(0));
original.add(new HeavyOjbect(1));
original.add(new HeavyOjbect(2));
ArrayList<Integer> copy = (ArrayList<HeavyOjbect>) original.clone();
copy.remove(0);

原始 -> [HeavyOjbect0,HeavyOjbect1,HeavyOjbect2]

复制-> [HeavyOjbect1,HeavyOjbect2]

正确的 ?

但我不知道克隆是做什么的。它会克隆每个 HeavyObject 吗?我的意思是如果克隆 1000 倍我的 ArrayList,内存会爆炸吗?

编辑:所以克隆

new HeavyOjbect(0) -> @10
new HeavyOjbect(1) -> @20
new HeavyOjbect(1) -> @30

original(ref1 to @10, ref1 to @20, ref1 to @30)
copy(ref2 to @10, ref2 to @20, ref2 to @30)

正确的 ?

谢谢

4

3 回答 3

6

http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#clone()

public Object clone()
返回此 ArrayList 实例的浅表副本。(元素本身不会被复制。)

只复制对您的 s 的引用;HeavyObject每个克隆ArrayList都将包含对完全相同对象的引用。不会创建新HeavyObject的 s。

编辑添加:这是“浅”和“深”副本之间的区别。如果它是一个深层副本,那么每个副本HeavyObject也会被制作,正如你所说......你的记忆会爆炸。

于 2013-02-14T04:56:56.883 回答
1

clone() method is used to create a copy of an object of a class which implements Cloneable interface. By default it does field-by-field copy as the Object class doesn't have any idea in advance about the members of the particular class whose objects call this method. So, if the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned. But, if the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object. So it will not does any memory explode.

于 2013-02-14T05:02:33.237 回答
0

在这份声明中

ArrayList<Integer> copy = original;

您正在引用copy引用也指向original对象。

如果您通过copy引用修改对象,它也会在original对象上发生变化。

克隆:

clone() 方法将提供同一对象的另一个副本,因此如果您更改copy对象,它将反映在original对象中。

于 2013-02-14T04:57:34.310 回答