Clone of Java objects

In the Java language, data types are divided into value types (basic data types) and reference types. Value types include simple data types such as int, double, byte, Boolean and char, and reference types include complex types such as classes, interfaces and arrays.

The main difference between shallow cloning and deep cloning is whether it supports the replication of member variables of reference types. They are described in detail below.

Shallow clone:

In shallow cloning, if the member variable of the prototype object is a value type, a copy will be copied to the cloned object; If the member variable of the prototype object is a reference type, copy the address of the reference object to the clone object, that is, the member variables of the prototype object and the clone object point to the same memory address.

Simply put, in shallow cloning, when an object is copied, only the member variables of itself and its value type are copied, while the member object of reference type is not copied.

The diagram is as follows:

The native clone method in the object class provides shallow clone support. You can implement the clonable interface and call the clone method of object to implement shallow clone for a class:

The execution results of the program are as follows:

In the example program, the value of the reference variable bar of F1 is changed, and the member variable bar of F2 is also affected. However, F2 is not affected by changing the value of the direct type member ID of F1.

It can be seen that the shallow clone can only the value of the direct type in the clone member variable, and the value of the application type is the address of the reference object.

Deep clone:

In deep clone, no matter whether the member variable of the prototype object is a value type or a reference type, it will be copied to the cloned object. Deep clone will also copy all reference objects of the prototype object to the cloned object.

Simply put, in deep cron, in addition to the object itself being copied, all member variables contained in the object will also be copied.

The diagram is as follows:

To make the above program support deep clone, we need to make some adjustments:

First, you need to add clone method support to the bar class:

Then modify the clone method of foo class:

The results are as follows:

At this point F2 is no longer affected by F1.

At this point, continue to think about what to do if there are reference type members in the bar, and if the reference type members in the bar also have their own reference type members?

It's a good thing to solve. I'm too lazy to explain.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>