我了解到,对于数组,clone
方法表现良好,我们可以使用它。但我认为数组所保存的元素类型应该实现 Cloneable
接口(interface)。让我举一些例子:
public class test {
public static void main(String[] args){
Test[] arr_t = new Test[1];
arr_t[0] = new Test(10);
Test[] an_arr = arr_t.clone();
an_arr[0]= new Test(5);
System.out.println(an_arr[0].test); //5
System.out.println(arr_t[0].test); //10
}
public static class Test{
public int test;
public Test(int test) {
this.test = test;
}
}
}
我认为 5 应该打印两次。原因是通过克隆数组,我们创建了新数组,其中包含对第一个数组所保存的对象的引用(因为元素的类型没有实现 Cloneable)。你就不能把事情理顺一下吗?
尚不清楚数组元素的类型是否需要实现Cloneable
。
最佳答案
这是一个简单的概念,但似乎很难解释。当您克隆数组时,内存中将有两个区数组,但它们的索引具有相同的值。
<小时/>在第二个数组 an_arr
中执行 an_array[0] = new Test(5)
时,您将在槽 0 中放置另一个引用。
但是克隆的索引 0 与克隆数组位于不同的位置。
如果您这样做,您的示例就是有效的
Test[] arr_t = new Test[1];
arr_t[0] = new Test(10);
Test[] an_arr = arr_t.clone();
an_arr[0].test = 5; // look here, I changed the object
System.out.println(an_arr[0].test); //5
System.out.println(arr_t[0].test); //5
现在两者将打印相同的值,因为它们持有对同一对象的相同引用,但存储该引用的位置不同。
关于java - 了解数组的克隆方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31051765/