Java Deep Copy And Shallow Copy

2640 ワード

In java,shallow copy means when you copy a list,the dst list elements actually share the same addresses with those of the src list,while deep copy means the dst list asks for a different memory to copy from the src list.
To do deep copy,one way is to define copy function in the class as a special form of constructor
see a example of deep copy
public class Student {
    
    private String birthday;
    private String name;
    
    public Student()
    {
        
    }
    public Student(String name,String birthday){
        this.birthday = birthday;
        this.name = name;
    }
    
    public Student copy()
    {
        Student stu =  new Student();
        stu.birthday = this.birthday;
        stu.name = this.name;
        return stu;
    }
    
    public void printDetails()
    {
        System.out.println(this.name+" "+this.birthday);
    }
    
}
    public static void main(String[] args) {
        ArrayList students = new ArrayList<>();
        Student s1 = new Student("wang", "19950629");
        Student s2 = new Student("sun", "19920411");
        Student s3 = new Student("lei", "19990927");
        students.add(s1);
        students.add(s2);
        students.add(s3);
        System.out.println("SRC:");
        students.forEach((student) -> {
            student.printDetails();
        });
        // deep copy
        ArrayList newStudentses = new ArrayList<>();
        students.forEach((student) -> {
            newStudentses.add(student.copy());
        });
        System.out.println("SRC after remove:");
        students.remove(2);
        students.forEach((student) -> {
            student.printDetails();
        });
        System.out.println("DST:");
        newStudentses.forEach((newStudents)->{
             newStudents.printDetails();
        });
        
    }

when a member of  the list is removed from the src list,the cloned list won't change since it is indeed like an individual
so the  results are 
SRC:
wang 19950629
sun 19920411
lei 19990927
SRC after remove:
wang 19950629
sun 19920411
DST:
wang 19950629
sun 19920411
lei 19990927

And to do shallow copy is easy, just add the elements of the src list to the dst list.They share the same elements
So the main difference in code is that,when add new elements to the dst list,deep copy uses the cloned guys while shallow copy uses the original objects,thus share the same address.