Java深入理解深拷貝和淺拷貝區別


Java中使用對象的父類的clone方法和直接賦值都是淺拷貝,例如:

class Student implements Cloneable {
    ...
    public Object clone() throws CloneNotSupportedException {
        Object object = super.clone();
        return object;
    }
}

public class Main {
    public static void main(String[] args) throws CloneNotSupportedException {
        Student student1 = new Student();
        Student student2 = (Student)student1.clone();
    }
}

class Student{
    ...
}

public class Main {
    public static void main(String[] args) {
        Student student1 = new Student();
        Student student2 = student1;
    }
}

效果是一樣的。

參考:

Java深入理解深拷貝和淺拷貝區別


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM