One, shallow copy, deep copy
A shallow copy copies a member variable in an object: if it is a basic type, the copy is the value of the base type, and if the property is a memory address (reference type), the memory address is copied;
Deep Copy, in addition to the basic type, the object referenced by the reference type is also copied, (the referenced object only requires a shallow copy; to make a deep copy, it is generally possible to use serialization and deserialization, or you can manually implement a deep copy of the reference object at all levels)
Second, realize:
Shallow copy: Implement Cloneable interface, rewrite Clone () method, Call parent class Super.clone () in Clone ().
Deep copy: 1. Implement the Cloneable interface, in addition to calling Super.clone (), and manually calling its clone () method on the reference type and assigning values;
2. Using serialization to achieve deep copy, implement Serializable interface, there is no need to rewrite the method;
Serialization can be combined with these two methods:
// when the object is serialized, if this method is implemented, the call Private void throws ioexception{ stream.defaultwriteobject (); Stream.writeobject (custom object);} // when the object is deserialized, if this method is implemented, the call Private void throws ioexception{ stream.defaultreadobject (); Stream.readobject ();}
Note: Neither clone nor serialization calls the object's construction method;
Serialization does not serialize static and transient-modified variables;
Code reference: Shallow copy and deep copy (talk about clone in Java)
Java serialization and Static
Shallow copy and serialization of Java deep copy