Java Deep Copy And Shallow Copy

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<Student> 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<Student> 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. 




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值