Today’s sharing started, please give us more advice ~

Today I’m going to share with you about deep copy and shallow copy of Java, which is simply to create an object that is exactly the same as a known object. Probably not used much in everyday coding, but this is a common interview question, and understand the principle of deep copy and shallow copy, for the so-called value passing or reference passing in Java will have a deeper understanding.

1. Five ways to create an object

  • Through the new keyword

This is the most common way to create an object by calling the class’s parameter or no-parameter constructor with the new keyword.

Object obj = new Object();

  • Through the Class newInstance() method

The default is to call the class’s no-argument constructor to create an object.

For example, Person p2 = (Person) class.forname (” com.ys.test.person “).newinstance ();

  • Through the newInstance method of the Constructor class

This is similar to the second method, which is done by reflection. Through the Java. Lang. Relect. Constructor class newInstance () method to specify a Constructor to create objects.

Person p3 = (Person) Person.class.getConstructors()[0].newInstance();

The second method actually creates an object using the Class’s newInstance() method, which internally calls the Constructor newInstance() method.

  • Using Clone method

Clone is A Clone method of the Object class. Using the Object a. lone() method, Clone creates an Object B with the same content as Object A.

Person p4 = (Person) p3.clone();

  • deserialization

Serialization is the process of taking Java object data from heap memory and somehow storing the object to a disk file or passing it to another network node (over the network). Deserialization is the process of restoring object data from disk files or network nodes to the Java object model.

2. The Clone method

In the Object.class class, the source is:

protected native Object clone() throws CloneNotSupportedException;
Copy the code

It doesn’t matter if you don’t understand it. All you need to know is that the way to use native modification is to tell the operating system that I won’t implement this method, and let the operating system implement it. We don’t need to know how to implement it, but we need to know that the clone method is used to copy objects and create a new object. So what is the relationship between this new object and the original object?

3. Primitive and reference types

In Java, data types fall into two broad categories: primitive types and reference types.

The basic types, also known as value types, are char, Boolean, and byte, short, int, long, float, and double.

Reference types include classes, interfaces, arrays, enumerations, and so on.

Java divides memory space into stacks and heaps. Primitive types store values directly on the stack, whereas reference types put references on the stack. The actual stored values are stored in the heap, and references in the stack point to data stored in the heap.

Both a and B are primitive types whose values are stored directly on the stack. C and D are declared by String, which is a reference type, and the reference address is stored on the stack and then refers to the memory space of the heap.

D = c; This statement assigns a reference to C to D, so c and D refer to the same heap memory space.

4. Shallow copy

Before we look at shallow copy, let’s implement it with a piece of code.

The code above is a primitive class Person to which we will assign. Next we generate a Person object and call its Clone method to copy a new object.

Note: To call the clone method of an object, you must have the class implement the Cloneable interface and override the Clone method.

The clone method has three attributes: a reference to pname (String), a reference to page (int), and a reference to Address. This is a custom class that also contains two attributes, pprovices and City.

Next, we create a Person class object P1, whose pname is Zhangsan,page is 21, Address class Address two attributes hubei province and Wuhan city. Next, we call the clone() method to copy another object, P2, and then print the contents of both objects.

Print the result from lines 1 and 3:

p1:com.bowen.demo.demo008.method1.Person@5dfe23e8  
p2:com.bowen.demo.demo008.method1.Person@583fb274
Copy the code

You can see that these are two different objects.

From the object contents printed in lines 5 and 6, the original object P1 and the cloned object P2 have exactly the same contents.

In the code, we only changed the property of the cloned object P2 to Jingzhou City, Hubei Province (the original object P1 was Wuhan City, Hubei Province), but from the print results of line 7 and line 8, the Address property of the original object P1 and the cloned object P2 have been modified.

In other words, the Address attribute of the object Person is cloned, but the reference is only copied, and they still point to the same memory space. When the Address attribute of one object is changed, the other object will also change.

Shallow copy: Create a new object and copy the non-static fields of the current object into the new object, or if the fields are of value type. If the field is a reference type, the reference is copied but not the referenced object. Therefore, the original object and its copy refer to the same object.

5. Deep copy

If you figure out the shallow copy, then the deep copy is easy to understand.

Deep copy: Create a new object and copy the non-static fields of the current object into the new object, regardless of whether the fields are of value type or reference type. When you modify anything in one object, it doesn’t affect anything in the other.

So how do you implement deep copy? The Clone class Object provides only shallow copies.

6. How to implement deep copy?

The principle of deep copy is to make the original object and the cloned object have reference type properties that do not point to the same heap. There are two ways to do this.

Method one: Override the clone() method internally for each reference type attribute

Since reference types cannot be deep copied, we split each reference type into primitive types for shallow copies. In the example above, the Person class has a reference type Address(String is also a reference type, but String is a bit special, as we’ll explain later), and we override the Clone method inside the Address class. As follows:

Address.class:

The clone() method of person.class:

@Override
	protected Object clone() throws CloneNotSupportedException {
		Person p = (Person) super.clone();
		p.address = (Address) address.clone();
		return p;
	}
Copy the code

Again, we find that the Address property of p2 has changed, but the Address property of P1 has not changed.

The problem with this approach is that the Person class has only one Address reference type and the Address class does not, so we just override the Clone method of the Address class. However, if the Address class also has a reference type, We would have to rewrite the Clone method as many times as there are reference types. If there are many reference types, the code would obviously be a lot of code, so this method would not be appropriate.

Method two: Use serialization

Serialization is writing an object to a stream for easy transfer, while deserialization is reading an object from the stream. Here the object written to the stream is a copy of the original object, which still exists in the JVM, so we can use the serialization of the object to produce a clone object, which can then be retrieved by deserialization.

Note that each class that needs to be serialized implements the Serializable interface. If a property does not need to be serialized, it can be declared transient, excluding it from the clone property.

Because serialization produces two completely independent objects, serialization can achieve deep copy no matter how many reference types are nested.

summary

In this article we’ll look at deep and shallow copies of Java, implemented by calling the Clone () method of the Object class. There is no end to learning and I hope I can help you!

Today’s share has ended, please forgive and give advice!