Java中浅拷贝和深拷贝的区别

119 阅读1分钟

浅拷贝定义

在拷贝一个对象时,对对象的基本数据类型的成员变量进行拷贝,但对引用类型的成员变量只进行引用的传递,并没有创建一个新的对象,当对引用类型的内容修改会影响被拷贝的对象。简而言之:浅拷贝仅仅复制所 拷贝 的对象,而不复制它所引用的对象。

浅拷贝样例如下

public class ShallowCopy {
    public static void main(String[] args) throws CloneNotSupportedException {
        Teacher teacher = new Teacher();
        teacher.setName("KONG");
        Student student = new Student();
        student.setName("TOM");
        student.setAge(18);
        student.setTeacher(teacher);
        Student studentCopy = (Student) student.clone();
        student.setName("JERRY");
        System.out.println("拷贝结束==");
        System.out.println(studentCopy.getName());
        System.out.println(studentCopy.getAge());
        System.out.println(studentCopy.getTeacher().getName());
        // 修改老师的信息
        teacher.setName("WANG");
        System.out.println("修改teacher之后==");
        System.out.println("student的teacher为: " + student.getTeacher().getName());
        System.out.println("studentCopy的teacher为: " + studentCopy.getTeacher().getName());

    }
}

class Teacher implements Cloneable {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    @Override
    protected Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
    
}

class Student implements Cloneable {
    private String name;
    private int age;
    private Teacher teacher;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }
}

demo运行结果如下

20220711183351020.png

浅拷贝后的studentCopy对象的teacher成员变量的值会跟着拷贝前student对象的teacher值的改变而改变,由此可见 浅拷贝仅仅复制所 拷贝 的对象,而不复制它所引用的对象。

再看深拷贝

只要修改一下Student类的clone()方法即可

20220711184806324.png

运行结果如下

20220711184514904.png

由此可见深拷贝之后的student对象和他引用的teacher对象都不是原来的对象了。

总结

java的clone()方法是浅拷贝,对象内属性引用的对象只会拷贝引用地址,而不会将引用的对象重新分配内存,相对应的深拷贝则会连引用的对象也重新创建。