在数组上调用clone()是否也克隆其内容? [英] Does calling clone() on an array also clone its contents?

查看:101
本文介绍了在数组上调用clone()是否也克隆其内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在类型A的对象数组上调用 clone()方法,它将如何克隆其元素?该副本是否会引用相同的对象?或者它会为每个人调用(类型A的元素).clone()吗?

If I invoke clone() method on array of Objects of type A, how will it clone its elements? Will the copy be referencing to the same objects? Or will it call (element of type A).clone() for each of them?

推荐答案

clone()创建一个浅表副本。这意味着不会克隆元素。 (如果他们没有实现 Cloneable 怎么办?)

clone() creates a shallow copy. Which means the elements will not be cloned. (What if they didn't implement Cloneable?)

您可能想要使用 Arrays.copyOf(..)用于复制数组而不是 clone()(尽管克隆适用于数组,不像其他任何东西)

You may want to use Arrays.copyOf(..) for copying arrays instead of clone() (though cloning is fine for arrays, unlike for anything else)

如果你想深度克隆,检查此答案

一个小例子来说明 clone()即使元素 Cloneable

A little example to illustrate the shallowness of clone() even if the elements are 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  
-----  

这篇关于在数组上调用clone()是否也克隆其内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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