Analysis of Java deep replication function and usage examples
This article describes the function and usage of Java deep replication. Share with you for your reference, as follows:
Write before:
What is deep replication? In Java, when creating an object, we usually have a reference to the object, When we change the value (attribute) of an object through a reference variable, the reference remains unchanged, but changes to the memory in the memory, that is, the object to which the reference refers. Generally, when we assign the reference to another reference variable or pass it as a parameter, only the reference is passed, that is, the reference points to "copy" A copy is given to another reference variable, and then the reference variable also points to the same object. A new object is not created in memory. In some cases, we need to "really copy" objects and create a copy of known objects, not just "copy" references, for backup or other operations.
So, how to achieve?
Let's talk about the idea first: first serialize the object into the stream, then deserialize it, and read it from the stream.
The following code is:
The above operation results are as follows (measured):
It can be seen that when only reference is passed or a new value is created according to the value of the object, it can only be called "shallow copy". When the properties of the original object change, the properties of the new object created according to the above method will also change; If deep copy is adopted, a new object will be copied. There is no relationship between the new object and the original object. The change of the attributes of the original object will not affect the new object, just like the meaning of copy
Above, if there is anything wrong, if you can point it out, thank you very much
For more Java related content, interested readers can view the special topics of this site: Java data structure and algorithm tutorial, summary of Java DOM node operation skills, summary of java file and directory operation skills, and summary of Java cache operation skills