In-depth explanation of JAVA object deep cloning

Source: Internet
Author: User

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 ();
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.