Shallow copy and serialization of Java deep copy

Source: Internet
Author: User
Tags shallow copy

One, shallow copy, deep copy

A shallow copy copies a member variable in an object: if it is a basic type, the copy is the value of the base type, and if the property is a memory address (reference type), the memory address is copied;

Deep Copy, in addition to the basic type, the object referenced by the reference type is also copied, (the referenced object only requires a shallow copy; to make a deep copy, it is generally possible to use serialization and deserialization, or you can manually implement a deep copy of the reference object at all levels)

  

Second, realize:

Shallow copy: Implement Cloneable interface, rewrite Clone () method, Call parent class Super.clone () in Clone ().

Deep copy: 1. Implement the Cloneable interface, in addition to calling Super.clone (), and manually calling its clone () method on the reference type and assigning values;

2. Using serialization to achieve deep copy, implement Serializable interface, there is no need to rewrite the method;

Serialization can be combined with these two methods:

// when the object is serialized, if this method is implemented, the call Private void throws ioexception{    stream.defaultwriteobject ();    Stream.writeobject (custom object);} // when the object is deserialized, if this method is implemented, the call Private void throws ioexception{    stream.defaultreadobject ();    Stream.readobject ();}

Note: Neither clone nor serialization calls the object's construction method;

Serialization does not serialize static and transient-modified variables;

Code reference: Shallow copy and deep copy (talk about clone in Java)

        Java serialization and Static

Shallow copy and serialization of Java deep copy

Related Article

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.