Java - deep and shallow copy

Catalog

1. shallow copy

2. deep copy

The Object class provides clone(), which can be used only after the subclass implements the clonable interface. You can customize clone() in the class.

protected native Object clone() throws CloneNotSupportedException; 

The Serializable and Cloneable interfaces do not have any methods, which are called identity interfaces.

1. shallow copy

The copied object still retains all references of the original object. As long as the references in any copied object (or original object) change, all objects will be affected.

/**
 * Shallow copy
 * Reference data type original object and clone object sharing
 * Author:qqy
 */
public class ShallowCopy {
    public static void main(String[] args) {
        Teacher1 teacher=new Teacher1("Teacher 1");
        teacher.setAge(30);
        teacher.setSkill("Sing");

        Student1 student1=new Student1("Student 1",20,teacher);
        System.out.println(student1);
        System.out.println(teacher);

        Student1 student2= (Student1) student1.clone();
        student2.setName("Student 2");
        student2.getTeacher().setSkill("Run");
        student2.getTeacher().setAge(35);

        System.out.println(student2);
        System.out.println(teacher);
    }
}

class Teacher1{
    private String name;
    private String skill;
    private int age;

    @Override
    public String toString() {
        return "Teacher1{" +
                "name='" + name + '\'' +
                ", skill='" + skill + '\'' +
                ", age=" + age +
                '}';
    }

    public Teacher1(String name) {
        this.name = name;
    }

    public void setSkill(String skill) {
        this.skill = skill;
    }

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

//If a class wants to call Clone(), it needs to implement the clonable interface
class Student1 implements Cloneable{
    private String name;
    private int age;
    private Teacher1 teacher;

    @Override
    public String toString() {
        return "Student1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", teacher=" + teacher +
                '}';
    }

    public Object clone(){
        try {
            return super.clone();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Student1(String name, int age, Teacher1 teacher) {
        this.name = name;
        this.age = age;
        this.teacher = teacher;
    }

    public void setName(String name) {
        this.name = name;
    }
    
    public Teacher1 getTeacher() {
        return teacher;
    }
}

2. deep copy

The copied object generates all the referenced new objects. Modifying any object will not affect other objects.

  • Using serialization to realize deep copy
    • Convert an object to a byte array and then a byte array to an object
    • There is no need to implement clonable interface, only Serializable interface
import java.io.*;

/**
 * Deep copy
 * Author:qqy
 */
public class DeepClone {
    public static void main(String[] args) {
        Teacher2 teacher = new Teacher2("Teacher 1");
        teacher.setAge(30);
        teacher.setSkill("Sing");

        Student2 student1 = new Student2("Student 1", 20, teacher);
        System.out.println(student1);
        System.out.println(teacher);

        Student2 student2 = student1.clone();
        student2.setName("Student 2");
        student2.getTeacher().setSkill("Run");
        student2.getTeacher().setAge(35);

        System.out.println(student2);
        System.out.println(teacher);
    }
}

class Teacher2 implements Serializable {
    private String name;
    private String skill;
    private int age;

    @Override
    public String toString() {
        return "Teacher1{" +
                "name='" + name + '\'' +
                ", skill='" + skill + '\'' +
                ", age=" + age +
                '}';
    }

    public Teacher2(String name) {
        this.name = name;
    }

    public void setSkill(String skill) {
        this.skill = skill;
    }

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

class Student2 implements Serializable {
    private String name;
    private int age;
    private Teacher2 teacher;

    @Override
    public String toString() {
        return "Student1{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", teacher=" + teacher +
                '}';
    }

    public Student2 clone() {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ObjectOutputStream outputStream = new ObjectOutputStream(out);
            outputStream.writeObject(this);
            byte[] data=out.toByteArray();

            ByteArrayInputStream in=new ByteArrayInputStream(data);
            ObjectInputStream inputStream=new ObjectInputStream(in);
            return (Student2) inputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    public Student2(String name, int age, Teacher2 teacher) {
        this.name = name;
        this.age = age;
        this.teacher = teacher;
    }

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

    public Teacher2 getTeacher() {
        return teacher;
    }
}

 

Keywords: Programming Java

Added by dimxasnewfrozen on Sat, 07 Dec 2019 10:31:59 +0200