Java shallow copy and deep copy

Source: Internet
Author: User

ext.: http://blog.csdn.net/u014727260/article/details/55003402

2 points to achieve clone:

The 1,clone method is a method of the object class, so any class will automatically have the method

2, not all classes can call the Clone method, because JAVAC requires the declaration shown by the programmer by declaring "implements Cloneable" on the class

Shallow Copy

A shallow copy is a bitwise copy of an object that creates a new object with an exact copy of the original object's property values. If the property is a base 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, so if one of the objects changes the address, it will affect the other object.

The class that implements the object copy must implement the Cloneable interface and overwrite the Clone () method.

Deep Copy

A deep copy copies all of the attributes and copies the dynamically allocated memory that the attribute points to. A deep copy occurs when the object is copied along with the object it refers to. A deep copy is slower and more expensive than a shallow copy.

Now in order to make a deep copy of the Clone object, it is necessary to clonable the interface, overwrite and implement the Clone method, except to invoke the Clone method in the parent class to get the new object, and also clone the reference variable in the class. If you only use the default Clone method in object, it is a shallow copy.

How to make a thorough deep copy

For the above example, how can you ensure that two body objects are completely independent? As long as the head object is copied, the face object will be copied a copy of it. This requires that the face class also implement the Cloneable interface, implement the Clone method, and copy the face object it refers to in the Clone method of the head object. The modified part of the code is as follows:

Java shallow copy and deep copy

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.