Deep copy and shallow copy of Java objects

Source: Internet
Author: User
Tags shallow copy
Shallow copy and deep copy concept

Shallow copy (Shallow clone): All variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object. In other words, a shallow copy simply duplicates the object being considered, not the object it refers to.
Deep copy (Deep clone): All the variables of the copied object contain the same values as the original object, removing those variables that refer to other objects. Variables that refer to other objects will point to new objects that have been copied, not those that are already referenced. In other words, a deep copy copies the objects that are referenced by the object being copied again.

The Clone () method of Java

(1) The Clone method copies a copy of the object and returns it to the caller. Generally, the clone () method satisfies:
① to any object x, there are X.clone ()!=x//The cloned object is not the same object as the original object;
② has X.clone () for any object X. getclass () = =x.getclass ()//Cloning the object is the same as the type of the original object;
③ if the Equals () method of object x is defined appropriately, then X.clone (). Equals (x) should be established;

(2) Cloning of objects in Java:
① in order to get a copy of the object, we can take advantage of the Clone () method of the Objects class.
② overrides the Clone () method of the base class in the derived class and declares it to be public.
③ in the Clone () method of the derived class, call Super.clone ().
④ implements the Cloneable interface in a derived class.

Deep copy and shallow copy 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.