Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Reference copy, shallow copy, deep copy

We copy an object to another object, this situation is called copy, and copy is divided into reference copy, shallow copy, deep copy, they refer to what it is, in the daily development process, it is very necessary to understand it.

Reference copy

A reference copy feels like an address reference, just a copy of the address, and all the addresses actually point to one object. The reference address is in the stack, and the actual object is in the heap. A reference copy is a copy of a reference address.

Graph of TD A (address) - > heap (heap memory) B (1) copy address - > heap [heap memory] C (copy address 2) - > heap [heap memory]

Every address points to the same place

 Person person = new Person();
 Person person1 = person;
Copy the code

This will change either the person or person1 properties.

Shallow copy

The meaning of shallow copy is somewhat complicated, so let’s summarize what shallow copy is. A shallow copy creates a new object that is not equal to the original object and has a different memory area, but has the same properties as the old object.

  • If the attribute is of a primitive type (int,double,long, Boolean, etc.), the value of the primitive type is copied.
  • If the property is a reference type, the memory address is copied (that is, the referenced object is copied but not copied)

Note: String is equivalent to a primitive data type when assigned by a constant. Since String is immutable, it cannot change the state of the original String. A new String is generated

How do you understand this? Let’s see the picture

Graph of TD A (address) - > X [1] heap memory object B (1) copy address - > [2] heap memory object Y C (copy address 2) - > Z [3] heap memory object X - > D (child attributes 1) Y - > D (child attributes 1) Z - > D (child attributes 1) X --> E(subattribute 2) Y --> E(subattribute 2) Z --> E(subattribute 2)

If it’s a little confusing, let’s see what it looks like.

How do you implement shallow copy?

  1. Implement the Cloneable interface on the class you want to copy and override its clone() method
  2. Call the clone() method of the class directly
** * Implements Cloneable /** * Implements Cloneable () method ** @override public Object Clone () {try {return super.clone(); } catch (CloneNotSupportedException e) { return null; }}Copy the code

Deep copy

Deep copy creates a new object that is completely independent of the original object, so no matter how many properties are modified, the properties in the other object will not change.

Look at the picture

How to implement deep copy.

Serialization is the accepted approach.

One neat way to do this, for example, is to convert an object to JSON, and then use JSON to convert an object.