Deep cloning of Java objects

Source: Internet
Author: User

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

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.