Java基础 深拷贝浅拷贝

时间:2021-07-23 19:49:24

Java基础 深拷贝浅拷贝

  • 非基本数据类型 需要new新空间
    ```
    class Student implements Cloneable{
    private int id;
    private String name;
    private Vector course;

    public Student(){
    try{
    Thread.sleep(1000);
    System.out.println("Student Constructor called.");
    }catch (InterruptedException e){
    e.printStackTrace();
    }
    }

    public String getName() {return name;}
    public void setName(String name) {this.name = name;}

    public int getId() {return id;}
    public void setId(int id) {this.id = id;}

    public Vector getCourse() {return course;}
    public void setCourse(Vector course) {this.course = course;}

    //浅拷贝
    public Student newInstance(){
    try{
    return (Student)this.clone();
    }catch (CloneNotSupportedException e){
    e.printStackTrace();
    }
    return null;
    }

    //深拷贝
    public Student deepClone(){
    try{
    Student cloning = (Student) super.clone();
    cloning.course = new Vector();
    return cloning;

    }catch (CloneNotSupportedException e){
    e.printStackTrace();
    }
    return null;

    }

}

public Object clone(){ //覆写clone(),深拷贝
try{
Student cloning = (Student) super.clone();
// 这里不能使用Student cloning = (Student) this.clone()的原因:
正在覆写本类的clone()方法,如果再调用本类的函数,即:this.clone(),就相当于无限递归无限死循环了,最终会崩溃的。所以这里:super.clone()。

    cloning.courses = new Vector();     //关键点:非基本数据类型的空间需要自己新开辟一块儿  
return cloning;
}catch(CloneNotSupportedException e){
e.printStackTrace();
}
return null;

}

```
Java基础 深拷贝浅拷贝

参考资料

谨慎覆盖clone
Java中的clone() 深拷贝 浅拷贝