Java shallow copy and deep copy (basic is also very important)

Java shallow copy and deep copy (basic is also very important)

You may just be ignorant of the copy of the object, or you didn't care about it, let's find out.

For the github base code https://github.com/chywx/JavaSE

Recently I learned C++, which is very similar to Java. Learning C++ on the MOOC.com is also a review of the basics of Java.

I understand that when the lecturer always emphasized that java transfer is only value transfer, there is no reference transfer, why have to repeat this? Since there is only value transfer, why also emphasized that it is not transfer by reference

What's wrong this is

 Only after learning C++ did I know that C++ has the argument of passing by value and passing by reference, but Java is just passing by value.

The simplest understanding is for method calls

For example, f(int a,int b) is value transfer, and the passed value will not be modified.

Another example is f(int &a,int &b), which is passed by reference, and the passed value will be modified

On the right track, talk about Java's shallow copy (Shallow Copy) and deep copy (Deep Copy).

Shallow copy (Shallow Copy): ① the basic data for the data type is the variable type member, shallow copy transfer a value directly, i.e. attribute values of the object to the new copy. Because there are two different data, modifying the value of the member variable of one of the objects will not affect the data copied by the other object. ②For a member variable whose data type is a reference data type, for example, a member variable is an array, an object of a certain class, etc., then the shallow copy will be passed by reference, that is, only the reference value (memory address) of the member variable Make a copy for the new object. Because in fact the member variables of both objects point to the same instance. In this case, modifying the member variable in one object will affect the value of the member variable in another object.

Learn through examples,

 One:

  Use constructor to implement copy

public class Person {
    public static void main(String[] args) {
        Son s = new Son(10);
        Person p1 = new Person("Ocean", s);
        Person p2 = new Person(p1);
        p1.setSonName("小海");
        p1.getSon().setAge(12);
        System.out.println("p1:" + p1);//p1:Person [sonName=小海, son=Son [age=10]]
        System.out.println("p2:" + p2);//p2:Person [sonName=the ocean, son=Son [age=10]]

    }

    private String sonName;
    private Son son;

   //Custom copy function
    public Person(Person person) {
        this.sonName = person.sonName;
        this.son = person.son;
    }

    public Person(String sonName, Son son) {
        super();
        this.sonName = sonName;
        this.son = son;
    }

    public String getSonName() {
        return sonName;
    }

    public void setSonName(String sonName) {
        this.sonName = sonName;
    }

    public Son getSon() {
        return son;
    }

    public void setSon(Son son) {
        this.son = son;
    }

    @Override
    public String toString() {
        return "Person [sonName=" + sonName + ", son=" + son + "]";
    }

}

class Son {
    private int age;

    public int getAge() {
        return age;
    }

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

    public Son(int age) {
        super();
        this.age = age;
    }

    @Override
    public String toString() {
        return "Son [age=" + age + "]";
    }

}

result

p1:Person [sonName=小海, son=Son [age=12]] p2:Person [sonName=大海, son=Son [age=12]]

For the above example, the person object has two members, a basic type and a reference type. The result is a copied object. The member of the basic type actually implements copy.

 two:

  To use the built-in clone method, you need to implement the cloneable interface, otherwise it will

Exception in thread "main" java.lang.CloneNotSupportedException:

public class Person2 implements Cloneable {
    public static void main(String[] args) throws CloneNotSupportedException {
        Son2 son1 = new Son2(10);

        Person2 person1 = new Person2("the sea", son1);
        Person2 person2 = (Person2) person1.clone();
        person2.setSon2Name("小海");
        person2.getSon2().setAge(12);
        System.out.println(person1);
        System.out.println(person2);
    }

    public Person2(String son2Name, Son2 son2) {
        super();
        this.son2Name = son2Name;
        this.son2 = son2;
    }

    private String son2Name;
    private Son2 son2;

    public String getSon2Name() {
        return son2Name;
    }

    public void setSon2Name(String son2Name) {
        this.son2Name = son2Name;
    }

    public Son2 getSon2() {
        return son2;
    }

    public void setSon2(Son2 son2) {
        this.son2 = son2;
    }

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

    @Override
    public String toString() {
        return "Person2 [son2Name=" + son2Name + ", son2=" + son2 + "]";
    }

}

class Son2 {
    private int age;

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Son2 [age=" + age + "]";
    }

    public Son2(int age) {
        super();
        this.age = age;
    }

}

 result:

Person2 [son2Name=大海, son2=Son2 [age=12]] Person2 [son2Name=小海, son2=Son2 [age=12]]

Use the built-in copy to achieve shallow copy

-------------------------------------------------- -------------------------------------------------

Deep copy

  Compared with the shallow copy, the modification of the reference type does not affect the value of the corresponding copy object. Each object on each layer is shallow copy = deep copy.

One:

  The clone method is still used, but it has to be rewritten manually.

Upload code

public class Person3 implements Cloneable {
    public static void main(String[] args) throws CloneNotSupportedException {
        Son3 son1 = new Son3(10);
        Person3 person1 = new Person3("the sea", son1);
        Person3 person2 = (Person3) person1.clone();
        person2.setSon2Name("小海");
        person2.getSon3().setAge(12);//Modify the value of the corresponding reference object.
        System.out.println(person1);
        System.out.println(person2);
    }

    public Person3(String son2Name, Son3 son3) {
        super();
        this.son2Name = son2Name;
        this.son3 = son3;
    }

    private String son2Name;
    private Son3 son3;

    public String getSon2Name() {
        return son2Name;
    }

    public void setSon2Name(String son2Name) {
        this.son2Name = son2Name;
    }

    public Son3 getSon3() {
        return son3;
    }

    public void setSon3(Son3 son3) {
        this.son3 = son3;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Person3 clone = (Person3) super.clone();
        clone.setSon3((Son3) clone.getSon3().clone());
        return clone;
    }

    @Override
    public String toString() {
        return "Person3 [son2Name=" + son2Name + ", son3=" + son3 + "]";
    }

}

class Son3 implements Cloneable {
    private int age;

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Son2 [age=" + age + "]";
    }

    public Son3(int age) {
        super();
        this.age = age;
    }

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

}

result:

Person3 [son2Name=Ocean, son3=Son2 [age=10]]

Person3 [son2Name=小海, son3=Son2 [age=12]]

Method Two:

Obviously for multiple objects, it is obviously very difficult. You can use another way,

After the object is serialized into a byte sequence, the entire object graph of the object will be serialized by default, and then the deep copy can be perfectly realized by deserializing.

public class Person4 implements Serializable {
    public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, IOException {
        Son4 son = new Son4(10);
        Person4 person1 = new Person4("Ocean", son);
       //Realize deep copy through serialization method
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        ObjectOutputStream oos=new ObjectOutputStream(bos);
        oos.writeObject(person1);
        oos.flush();
        ObjectInputStream ois=new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        Person4 person2=(Person4)ois.readObject();
        person1.setSon4Name("小海");
        person1.getSon4().setAge(12);
        System.out.println(person1.toString());
        System.out.println(person2.toString());
    }

    public Person4(String son4Name, Son4 son4) {
        super();
        this.son4Name = son4Name;
        this.son4 = son4;
    }

    private String son4Name;
    private Son4 son4;

    public String getSon4Name() {
        return son4Name;
    }

    public void setSon4Name(String son4Name) {
        this.son4Name = son4Name;
    }

    public Son4 getSon4() {
        return son4;
    }

    public void setSon4(Son4 son4) {
        this.son4 = son4;
    }

    @Override
    public String toString() {
        return "Person4 [son4Name=" + son4Name + ", son4=" + son4 + "]";
    }
}

class Son4 implements Serializable {
    private int age;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Son2 [age=" + age + "]";
    }

    public Son4(int age) {
        super();
        this.age = age;
    }

}

This is the implementation of serialization interface scheme, nice. 

perfect!!! in place

 Record the songs you hear.

    Peerless
            (Zhang Kefan)
All kinds of temptations in the world
Don't be surprised, don't disturb my dreams
The high mountain road is far away from me
Track your beautiful smile
I only understood when I climbed up and called
Always heartache for you
Bowing her head and shaking Huaying
Dongfeng is making fun of
The confusion of the world
I guessed wrong because of you
Water and moonlight blend again
Describe the bright night sky
Life and death
As calm as a mad flower and fallen leaves
When everything disappears like a dream
Just in the distant mountains, it was sealed by peerless dust            
Reference: https://cloud.tencent.com/developer/article/1335897 Java shallow copy and deep copy (basic is also very important)-Cloud + Community-Tencent Cloud