package com.example.test1;
/**
*
* 只调用super.clone()实现的是浅拷贝,需要再对其成员变量
* 再次进行拷贝才能实现真正的深拷贝。
*
*/
class TestCloneObject implements Cloneable{
private int[] arr;
{
System.out.println("TestCloneObject instance init 1");
}
public TestCloneObject(int[] arr){
this.arr = arr;
System.out.println("TestCloneObject instance init 2");
}
public TestCloneObject clone() throws CloneNotSupportedException {
TestCloneObject tmp = (TestCloneObject)super.clone();
tmp.arr = arr.clone(); //注释掉这句话之后,test1对象修改数组会导致test2中数组也发生修改
return tmp;
}
public void setIndex(int index, int value){
arr[index] = value;
}
public String toString(){
StringBuilder str = new StringBuilder();
str.append("[");
for (int i = 0; i < arr.length; i++){
str.append(arr[i] + ", ");
}
str.append("]");
return str.toString();
}
}
public class TestDemo {
public static void main(String[] args) throws CloneNotSupportedException {
// TODO Auto-generated method stub
int[] intArr = {1,2,3,4,5,6};
TestCloneObject test1 = new TestCloneObject(intArr);
TestCloneObject test2 = test1.clone();
System.out.println(test1);
System.out.println(test2);
test1.setIndex(0, 0);
System.out.println(test1);
System.out.println(test2);
}
}
17.Cloneable接口练习
最新推荐文章于 2020-05-02 22:17:01 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)