Clone, deep copy, and shallow copy

Source: Internet
Author: User

Shallow copy: copy an object. If the object exists inside the object and points to another object, no value is assigned.

Deep copy: in addition to the value assignment object itself, it also copies the objects referenced inside the object.

To better express the differences between the two, use the illustration.

Assume that there is an object A, which contains the reference of two objects A1 and A2.

After performing a shortest copy on a, the object B is obtained, but A1 and A2 are not copied:

Perform a deep copy on Object A to obtain object B. At the same time, A1 and A2 are also copied along with their references:

In the above section, we have some knowledge about the concepts of shallow copy and deep copy. Next we will discuss Java cloning.

In the most basic object class, there is a local method clone (). To avoid creating each class with the clone capability by default, JDK sets this method as protected. Object. Clone () will check the size of the original object, and free up enough memory for the new object to copy all binary bits from the original object to the new object. This is called "bitwise replication ". Before object. Clone () is started, the system checks whether a class can be cloned, that is, whether it implements the cloneable interface. If not, the object. Clone () method throws a clonenotsupportedexception exception, indicating that we cannot clone it.

According to the above description, if you want to use object. clone () is used to clone objects. Note the following two points: 1. Call super. clone () and set the clone method to public; 2. Implement the cloneable interface.

In additionJava serializationYou can also perform cloning.

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.