如果我在类型A的对象数组上调用clone()
方法,它将如何克隆其元素?副本将引用相同的对象吗?还是会为它们每个调用(element of type A).clone()
?
最佳答案
clone()
创建一个浅拷贝。这意味着将不会克隆元素。 (如果他们没有实现Cloneable
怎么办?)
您可能需要使用Arrays.copyOf(..)
而不是clone()
复制数组(尽管克隆适用于数组,与其他方法不同)
如果要深度克隆,请check this answer
一个小例子来说明clone()
的浅浅,即使元素是Cloneable
:
ArrayList[] array = new ArrayList[] {new ArrayList(), new ArrayList()};
ArrayList[] clone = array.clone();
for (int i = 0; i < clone.length; i ++) {
System.out.println(System.identityHashCode(array[i]));
System.out.println(System.identityHashCode(clone[i]));
System.out.println(System.identityHashCode(array[i].clone()));
System.out.println("-----");
}
打印品:
4384790
4384790
9634993
-----
1641745
1641745
11077203
-----
关于java - 在数组上调用clone()是否还会克隆其内容?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5821851/