之前看了又人发帖子问数组是不是个类,众说纷纭,个人认为他应该是类,因为他有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是一个全新的克隆出来的对象?

解决方案 »

  1.   

    即便数组时类的话,Test实现Cloneable了,
    但是Test[]没有实现呀,Test[]与Test不是相同的Type
      

  2.   

    我知道Test[]没有实现,我不是在问有没有办法么!
      

  3.   

    你没有在你的类中覆盖clone方法,所以它调用的是object的clone,此方法执行的是该对象的“浅表复制”,而不“深层复制”操作,如果你想用你的clone覆盖object的clone的话,你会发现,你首先必须用super.clone();来获得一个浅表复制,然后你可以用这个浅表复制来继续获得一个深层的复制
      

  4.   

    API 原文:Note that all arrays are considered to implement the interface Cloneable.问题的难点在于没有办法给一个数组类“[LTest;” 重新定义一个public Object clone()方法来进行深度克隆。楼主要是知道答案就公布吧!
      

  5.   

    确实如此,public class Test implements Cloneable {
        
        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方法
      

  6.   

    恩,我知道,我就是在问有没有办法让能够重写数组的clone方法?他究竟是个什么东西???
      

  7.   

    9楼说的对啊,所以直接clone基本类型数组是没问题的
    深clone的话,数组是java固有的一个类型,也是类,但不是自己新编的类型啊
    所以你无法自己定义一个数组去implement Cloneable也不能去重写Object的clone方法来完成深克隆
    解决这个问题的方法是使用容器类要么把Test数组的元素克隆一份从新赋值给另一个数组
      

  8.   

    下面虽然是深克隆,但是和数组对象无关。。数组没办法深克隆public class Test implements Cloneable {
        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();
        }
    }
      

  9.   

    另外在API中看到一段话:
    每个数组属于被映射为 Class 对象的一个类,所有具有相同元素类型和维数的数组都共享该 Class 对象。