Clone方法——深复制与浅复制

Author Avatar
ahscuml 3月 18, 2018
  • 在其它设备中阅读本文章

在学习clone方法的时候产生的一点小思考

如果使用clone方法必须实现Cloneable方法。
在复制过程中存在深复制与浅复制。浅复制仅仅复制基本类型,对于引用类型则没有完全复制,仅仅是引用而已。深复制则不同,全部复制。

浅复制

public class CloneTest {
    public static void main(String[] args) throws CloneNotSupportedException {
    Father father = new Father(50,"Father");
    Father father1 = (Father) father.clone();
    father1.setAge(10);
    father1.setName("Father1");
    System.out.println(father + " " +father.getAge() + " " + father.getName());
    System.out.println(father1 + " " +father1.getAge() + " " + father1.getName());
  }
}

输出结果是

Clone.Father@677327b6 50 Father
Clone.Father@14ae5a5 10 Father1

事实证明,使用clone进行的拷贝对于基本数据类型是进行新建空间复制过去的。

public class Father implements Cloneable {
    private String name;
    private int age;
    private ID id;    
    public Father(ID id,String name,int age){
        this.id = id;
        this.name = name;
        this.age = age;
    }    
    public void setId(ID id){
        this.id = id;
    }    
    public ID getId() {
        return id;
    }
    @Override
        public Object clone() throws  CloneNotSupportedException{
        Father father = (Father)super.clone();
        return father;
        }
}

public class ID {
    private int ID;    
    public void setID(int ID){
        this.ID = ID;
    }    
    public int getID(){
        return ID;
    }
}

public class CloneTest {
    public static void main(String[] args) throws CloneNotSupportedException {
        ID id = new ID();
        id.setID(1);
        Father father = new Father(id,"Father",40);
        Father father1 = (Father)father.clone();
        System.out.println(father.getId().getID());
        System.out.println(father1.getId().getID());
        id.setID(2);
        System.out.println(father.getId().getID());
        System.out.println(father1.getId().getID());

    }
}

输出结果为:

1
1
2
2

可见修改一个ID,两个对象都改变了ID,所以可以发现,两个ID使用的都是同一块地址,所以修改ID才会造成两个对象同时改变地址。

深复制

深复制的实现是通过将浅复制实现cloneable

This blog is under a CC BY-NC-SA 4.0 Unported License
本文链接:https://ahscuml.github.io/clone方法—深复制与浅复制/