In real-world programming, you'll encounter situations where you need to use cloning, for example, to get a very complex object, instead of using new to create a new object and assigning values to individual domains, you might as well clone an existing object directly. The application of this technology is not uncommon, the following to see several cases of cloning.
Error cloning:
1. Manipulating objects with "="
Reason: using "=" to manipulate the object, just modify the object's reference, when the two variables point to an object
2. Comparing objects with "= ="
Reason: using "= =" to compare objects, just to determine the memory address of two objects is consistent, rather than to determine whether the domain of two objects is consistent
Shallow clone:
Using the Clone () method, the method is declared as follows:
Public Object Clone () throws Clonenotsupportedexception
By default, this method implements the shallow cloning function. To support a mutable reference type, the reference type is also cloned when the method needs to be rewritten. This requires that the reference type also overrides the method, and the class that provides the cloning capability needs to implement the Cloneable interface, otherwise the clone () method is thrown clonenotsupportedexception.
Deep Cloning and serialization:
1. For deep clones, it can be cumbersome to rewrite the Clone () method in order to replicate the fields if the class has many reference types. If the domain of the reference type is also made up of reference types, you should consider implementing a deep clone using serialization.
2. Serialization can write any object to the stream, depending on the type of stream, the object can be written to a file, or the object can be written to a byte array. Cloning an object typically does not require saving first, so a byte array is used. Once the write is complete, it can be cloned by reading it out. It is relatively straightforward to write the clone () method without considering the domain of the reference type, but requires that the reference type also implements the serializable interface.
Considerations for cloning using serialization:
(1) For any serialized object, it is required to implement the Serializable interface
(2) If there is a reference type in the domain of the class, it is required that the reference type also implements the serializable interface, and so on.
(3) serialization is slower than cloning each reference type domain directly
Choose the appropriate cloning method:
If the fields of the class are basic or non-mutable, you can use shallow clones, otherwise deep clones are used. If the domain of a class is more complex, it can be implemented in a serialized way, or a deep clone should be implemented using a replication domain.
Java Cloning and serialization