Sometimes, we need to copy all the values of object A to object B (B = A). However, by assigning values with equal signs, you will find that when an object Value in B changes, at the same time, it will also modify the value of the corresponding object in!
Maybe you will say that using clone () is not enough ?! Your idea is only half correct, because when using clone (), other complex types (such as collections and objects) except the basic data and String types are not affected) it will still be affected! Unless you clone () The complex types of each object, but if the hierarchy of an object is very deep, the clone () is very complex and may be omitted!
Since copying objects with equal signs and clone () will affect the original objects, what should we do to ensure that the copied objects do not affect the original objects?
In fact, it is very simple to use the object for deep cloning. This clone achieves that the cloned object is independent from the original object!
Principle of object deep cloning:Serialize the object and write it in the output stream. Because the object written in the stream is a copy, the original object is still in the JVM. Then, convert the output stream to the input stream, write the object deserialization! In this way, the object is cloned in depth, and the two cloned objects are completely independent from each other!
You will find that the object's deep cloning is actually using the serialization and deserialization of the object, so the object to be deeply cloned must implement the Serializable interface!
The implementation code for deep cloning is as follows:
Copy codeThe Code 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 ();
}