之前看了又人发帖子问数组是不是个类,众说纷纭,个人认为他应该是类,因为他有Object的所有方法,而且还有自己的属性length,所以他应该属于类,当然这不是今天讨论的主题,今天讨论的主题是深度克隆
public class Test implements Cloneable {
T t = new T(); public static void main(String[] args) throws CloneNotSupportedException {
Test[] test1 = { new Test()};
Test[] test2 = test1.clone();
System.out.println(test1[0].t == test2[0].t);// 问题
}
}class T implements Cloneable {}有没有办法让test2[0].t是一个全新的克隆出来的对象?
public class Test implements Cloneable {
T t = new T(); public static void main(String[] args) throws CloneNotSupportedException {
Test[] test1 = { new Test()};
Test[] test2 = test1.clone();
System.out.println(test1[0].t == test2[0].t);// 问题
}
}class T implements Cloneable {}有没有办法让test2[0].t是一个全新的克隆出来的对象?
但是Test[]没有实现呀,Test[]与Test不是相同的Type
T t = new T(1);
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
Test tc=(TestClone)super.clone();
tc.t=new T(2);
return tc;
} public static void main(String[] args) throws CloneNotSupportedException {
Test[] test1 = { new Test()};
Test[] test2 = test1.clone();
System.out.println((test1[0].t).equals(test2[0].t));// 问题
System.out.println(test1[0].t == test2[0].t);// 问题
}
} class T { int i; public T(int i) {
this.i=i;
}
}我给TestClone重写了clone,但Test[]本身是数组,每次调用的都还是object的clone,只能浅表复制,问题就在于不能为数组重写clone方法
深clone的话,数组是java固有的一个类型,也是类,但不是自己新编的类型啊
所以你无法自己定义一个数组去implement Cloneable也不能去重写Object的clone方法来完成深克隆
解决这个问题的方法是使用容器类要么把Test数组的元素克隆一份从新赋值给另一个数组
T t = new T(); public static void main(String[] args) throws CloneNotSupportedException {
Test[] test1 = { new Test()};
Test[] test2 = {(Test)test1[0].clone()};
System.out.println(test1[0].t == test2[0].t);//
}
public Test clone() throws CloneNotSupportedException {
Test test = (Test)super.clone();
test.t = (T)t.clone();
return test;
}
}class T implements Cloneable {
public T clone() throws CloneNotSupportedException {
return (T)super.clone();
}
}
每个数组属于被映射为 Class 对象的一个类,所有具有相同元素类型和维数的数组都共享该 Class 对象。