Shallow copy: copy an object. If the object exists inside the object and points to another object, no value is assigned.
Deep copy: in addition to the value assignment object itself, it also copies the objects referenced inside the object.
To better express the differences between the two, use the illustration.
Assume that there is an object A, which contains the reference of two objects A1 and A2.
After performing a shortest copy on a, the object B is obtained, but A1 and A2 are not copied:
Perform a deep copy on Object A to obtain object B. At the same time, A1 and A2 are also copied along with their references:
In the above section, we have some knowledge about the concepts of shallow copy and deep copy. Next we will discuss Java cloning.
In the most basic object class, there is a local method clone (). To avoid creating each class with the clone capability by default, JDK sets this method as protected. Object. Clone () will check the size of the original object, and free up enough memory for the new object to copy all binary bits from the original object to the new object. This is called "bitwise replication ". Before object. Clone () is started, the system checks whether a class can be cloned, that is, whether it implements the cloneable interface. If not, the object. Clone () method throws a clonenotsupportedexception exception, indicating that we cannot clone it.
According to the above description, if you want to use object. clone () is used to clone objects. Note the following two points: 1. Call super. clone () and set the clone method to public; 2. Implement the cloneable interface.
In additionJava serializationYou can also perform cloning.