Java之浅拷贝与深拷贝

Posted 凉月缘

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java之浅拷贝与深拷贝相关的知识,希望对你有一定的参考价值。

----?浅拷贝

--- 概念

   被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。简单说,浅拷贝就是只复制所考虑的对象,而不复制它所引用的对象

--- 实现方式

  继承自java.lang.Object类的Cloneable接口,实现clone()方法

--- 举个栗子

package com.xxg;

//浅拷贝
public class ShallowCopy {
    public static void main(String[] args) throws CloneNotSupportedException {
        Teacher teacher = new Teacher();
        teacher.setName("Delacey");
        teacher.setAge(29);
        
        Student student1 = new Student();
        student1.setName("Dream");
        student1.setAge(18);
        student1.setTeacher(teacher);
        
        Student student2 = (Student) student1.clone();
        System.out.println("拷贝后");
        System.out.println("student2: "+student2.getName());
        System.out.println("student2: "+student2.getAge());
        student1.setAge(20);
        System.out.println("属性值修改后");
        System.out.println("student1: "+student1.getAge());
        System.out.println("student2: "+student2.getAge());
        System.out.println("student2.teacher_name: "+student2.getTeacher().getName());
        System.out.println("student2.teacher_age: "+student2.getTeacher().getAge());
        System.out.println("修改老师的信息后-------------");
        
       // 修改老师的信息
        teacher.setName("Jam");
        System.out.println("student1: "+student1.getTeacher().getName());
        System.out.println("student2: "+student2.getTeacher().getName());
    }
}

class Teacher implements Cloneable{
    private String name;
    private int age;
    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;
    }
    @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;
    }
    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        return super.clone();
    }
    
}
View Code

--- 结果

--- 内存图

 ----?深拷贝

--- 概念

    深拷贝是一个整个独立的对象拷贝,深拷贝会拷贝所有的属性,并拷贝属性指向的动态分配的内存。当对象和它所引用的对象一起拷贝时即发生深拷贝。深拷贝相比于浅拷贝速度较慢并且花销较大。简而言之,深拷贝把要复制的对象所引用的对象都复制了一遍。

--- 实现方式

  一种是通过继承java.lang.Object类的Cloneable接口,重写clone方法;另外一种是通过实现对象序列化的方式,使对象实现Serializable接口,然后把对象(实际上只是对象的一个拷贝,原先的对象依然在JVM里面)写到一个流里,再从流里读出来,便可以重建对象。

--- 举个栗子

CloneTest2 深复制

public class CloneTest2
{
    public static void main(String[] args) throws Exception
    {
        Teacher teacher = new Teacher();
        teacher.setName("Teacher Zhang");
        teacher.setAge(40);

        Student2 student1 = new Student2();
        student1.setName("ZhangSan");
        student1.setAge(20);
        student1.setTeacher(teacher);

        Student2 student2 = (Student2) student1.clone();
        System.out.println("拷贝得到的信息");
        System.out.println(student2.getName());
        System.out.println(student2.getAge());
        System.out.println(student2.getTeacher().getName());
        System.out.println(student2.getTeacher().getAge());
        System.out.println("-------------");

        // 修改老师的信息
        teacher.setName("Teacher Zhang has changed");
        System.out.println(student1.getTeacher().getName());
        System.out.println(student2.getTeacher().getName());

        // 两个引用student1和student2指向不同的两个对象
        // 但是两个引用student1和student2中的两个teacher引用指向的是同一个对象
        // 所以说明是浅拷贝

        // 改为深复制之后,对teacher对象的修改只能影响第一个对象
    }
}

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

    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;
    }

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

}

class Student2 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;
    }

    @Override
    public Object clone() throws CloneNotSupportedException
    {
        // 浅复制时:
        // Object object = super.clone();
        // return object;

        // 改为深复制:
        Student2 student = (Student2) super.clone();
        // 本来是浅复制,现在将Teacher对象复制一份并重新set进来
        student.setTeacher((Teacher) student.getTeacher().clone());
        return student;
    }

}
View Code

--- 结果

拷贝得到的信息
ZhangSan
20
Teacher Zhang
40
-------------
Teacher Zhang has changed
Teacher Zhang

--- 内存图

 

--- 举个栗子(序列化实现)

package com.xxg;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

//序列化实现深拷贝
public class DeepCopyServiable {

 public static void main(String[] args) throws Exception {
    
     Teacher3 t = new Teacher3();
     t.setName("Teacher Wang");
     t.setAge(50);

     Student3 s1 = new Student3();
     s1.setAge(20);
     s1.setName("ZhangSan");
     s1.setTeacher(t);

     Student3 s2 = (Student3) s1.deepClone();

     System.out.println("拷贝得到的信息:");
     System.out.println(s2.getName());
     System.out.println(s2.getAge());
     System.out.println(s2.getTeacher().getName());
     System.out.println(s2.getTeacher().getAge());
     System.out.println("---------------------------");

     // 将复制后的对象的老师信息修改一下:
     s2.getTeacher().setName("New Teacher Wang");
     s2.getTeacher().setAge(28);

     System.out.println("修改了拷贝对象的教师后:");
     System.out.println("拷贝对象的教师:");
     System.out.println(s2.getTeacher().getName());
     System.out.println(s2.getTeacher().getAge());
     System.out.println("原来对象的教师:");
     System.out.println(s1.getTeacher().getName());
     System.out.println(s1.getTeacher().getAge());
}

}
class Teacher3 implements Serializable
{
    private String name;
    private int age;

    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;
    }

}

class Student3 implements Serializable
{
    private String name;
    private int age;
    private Teacher3 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 Teacher3 getTeacher()
    {
        return teacher;
    }

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

    public Object deepClone() throws Exception
    {
        // 序列化
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);

        oos.writeObject(this);

        // 反序列化
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);

        return ois.readObject();
    }

}
View Code

--- 结果

----?其他

?clone方法是Object的方法,为什么还要实现cloneable接口?

  Cloneable接口是不包含任何方法的具体实现,仅仅作为一个识别标志,而且这个标志也仅仅是针对 Object类中clone()方法的,但是如果没有实现该接口,Object的clone()方法就会抛出ClassNotSupportedException异常

?为什么实现Serializable接口,同时需要一个serialVersionUID

  当一个类被序列化时,并且没有定义字段serialVersionUID,编译器eclipse会提示如下

 

在Eclipse中有两种生成方式:

  一个是默认的1L;

  private static final long serialVersionUID = 1L;

  一个是根据类名、接口名、成员方法及属性等来生成一个64位的哈希字段,比如:

  private static final long serialVersionUID = -932183802511122207L;

  如果你没有考虑到兼容性的问题,就把它关掉,不过有这个功能是好的,只要任何类别实现了Serializable接口,如果没有加入serialVersionUID,Eclipse都会给你提示,这个serialVersionUID为了让该类别Serializable向后兼容。

  如果你的对象序列化后存到硬盘上面后,你却更改了类的field(增加或减少或改名),当你反序列化时,就会出现异常,这样就会造成不兼容性的问题。

  但当serialVersionUID相同时,它就会将不一样的field以type的缺省值Deserialize,这个可以避开不兼容性的问题。

参考资料:

    java如果clone为什么要必须实现Cloneable接口? 

   【Java深入】深拷贝与浅拷贝详解

  Java 深拷贝和浅拷贝 利用序列化实现深拷贝

 

以上是关于Java之浅拷贝与深拷贝的主要内容,如果未能解决你的问题,请参考以下文章

React之浅拷贝与深拷贝

小tips:JS之浅拷贝与深拷贝

lua踩坑之浅拷贝与深拷贝

lua踩坑系列之浅拷贝与深拷贝

Python模块-copy

Java专题十九:浅拷贝与深拷贝