In depth explanation of deep cloning of JAVA objects

  • 2020-04-01 01:58:41
  • OfStack

Sometimes, we need to copy all the values of object A to object B (B = A), but by using the equal sign you will find that when the value of an object in B changes, it will also change to the value of the corresponding object in A!

"Clone ()," you might say. ! You're only half right, because with clone(), other complex types (collections, objects, etc.) are still affected except for the basic data and String types! Unless you have clone() for each complex type of object, but if an object is very deep, then clone() is very complex, and there may be a miss!
Since using the equal sign and clone() to copy an object will have an effect on the original object, how can we do so that the copied object does not have any effect on the original object?

In fact, it is very simple, with the object of the depth of cloning, this cloning after the realization of the cloning of the object and the original object is independent!
Deep cloning principle of object: Serialize the object and write it in the output stream, because the object written in the stream is a copy and the original object is still in the JVM. Then convert the output stream to the input stream, deserialize the object and write it out! In this way, the object of the depth of cloning, cloning of the two objects completely independent, do not affect each other!

You will find that the deep cloning of an object is actually the serialization and deserialization of the utilized object, so all objects to be deeply cloned should implement the Serializable interface!

The implementation code of deep cloning is as follows:

public Object copy() throws IOException, ClassNotFoundException{
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   ObjectOutputStream oos = new ObjectOutputStream(bos);
   oos.writeObject(this);
   ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
   return ois.readObject();
  }

Related articles: