Sometimes, we need to copy all the values of object A to object B (b = A), but you will find that when an object value in B changes, it also changes to the value of the corresponding object in a!
Perhaps you would say, with clone () do not do it?! Your idea is only half right, because when you use Clone (), other complex types (such as collections, objects, and so on) will be affected in addition to the underlying data and string types! Unless you clone () the complex type in each object, the clone () is very complex and can be omitted if the object has a very deep hierarchy!
Since copying an object with the equals sign and Clone () will have an effect on the original object, what should be done to make the copied object have no effect on the original object?
In fact, it is very simple, with the depth of the object cloning, this cloning to achieve the cloned object and the original object is independent of!
Object deep Cloning Principle: The object is serialized and written in the output stream, because the object written in the stream is a copy, the original object is still in the JVM, and then the output stream into the input stream, the object is deserialized after the write! In this way, the object is deeply cloned, and the cloned two objects are completely independent from each other.
You will find that the object's deep cloning is actually the use of the object's serialization and deserialization, so the object to be deeply cloned to implement the Serializable interface!
The implementation code for deep cloning is as follows:
1 PublicObject copy ()throwsIOException, classnotfoundexception{2Bytearrayoutputstream BOS =NewBytearrayoutputstream ();3ObjectOutputStream Oos =NewObjectOutputStream (BOS);4Oos.writeobject ( This);
5ObjectInputStream Ois =NewObjectInputStream (NewBytearrayinputstream (Bos.tobytearray ()));6 returnOis.readobject ();7}
Deep cloning of Java objects