Simple analysis of Java's shallow copy and deep copy

Source: Internet
Author: User
Tags shallow copy

Any class in Java that implements the Cloneable interface can replicate a copy of itself and pass it to the caller by calling the Clone () method. Generally, the clone () method satisfies:
(1) For any object x, there is X.clone ()!=x, that is, the cloned object is not the same object as the original object.
(2) For any object x, there is X.clone (). GetClass () ==x.getclass (), that is, the Clone object is the same as the type of the original object.
(3) if the Equals () method of object x is defined appropriately, then X.clone (). Equals (x) should be established.

 /*** Creates and returns a copy of this object. The precise meaning * of "copy" may depend on the class of the object. The general * Intent are that, for any object {@codex}, the expression: * <blockquote> * <pre> * x.clone ()! = x</pre></blockquote> * Would be true, and that the expression: * <blockquote> * <pre> * X.clone (). GetClass () = = X.getc Lass () </pre></blockquote> * would be {@codetrue}, but these is not absolute requirements. * While it was typically the case: * <blockquote> * <pre> * X.clone (). Equals (x) </pre>< ;/blockquote> * would be {@codetrue}, this is a absolute requirement. * <p> * By convention, the returned object should is obtained by calling * {@codeSuper.clone}. If a class and all of its superclasses (except * {@codeObject}) Obey this convention, it'll be is the case that * {@codeX.clone (). GetClass () = = X.getclass ()}. * <p> * By convention, the object returned by this method should being independent * of this object (which is B  Eing cloned). To achieve this independence, * it may is necessary to modify one or more fields of the object returned * by {@codeSuper.clone} before returning it. Typically, this means * copying no mutable objects that comprise the internal ' deep structure ' * of the object be  ing cloned and replacing the references to these * objects with references to the copies.  If A class contains only * primitive fields or references to immutable objects and then it's usually * the case that No fields in the object returned by {@codeSuper.clone} * need to be modified. * <p> * The method {@codeClone} for class {@codeObject} performs a * specific cloning operation. First, if the class of this object does * not implement the interface {@codecloneable}, then A * {@codeClonenotsupportedexception} is thrown. Note that all arrays * is considered to implement the interface {@codecloneable} and that * The return type of the {@codeClone} Method of an array type {@codet[]} * is {@codet[]} where T is any reference or primitive type. * Otherwise, this method creates a new instance of the class "this * object" and "initializes all it" with Exac tly the contents of * the corresponding fields of this object, as if by assignment; The * contents of the fields is not themselves cloned.     Thus, this method * performs a "shallow copy" of the "of" of this object, "a" and "deep copy" operation. * <p> * The class {@codeObject} does not itself implement the interface * {@codecloneable}, so calling the {@codeClone} method on a object * whose class is {@codeObject} would result in throwing a * exception at run time. *     * @returnA clone of this instance. * @throwsclonenotsupportedexception If the object ' s class does not * support the {@codeCloneable} interface. Subclasses * that override the {@codeClone} Method can also * Throw this exception to indicate a instance cannot *     Be cloned. * @seejava.lang.Cloneable*/    protected nativeObject Clone ()throwsClonenotsupportedexception;

First look at the definition of shallow copy and deep copy:

Shallow copy: Use a known instance to assign a value to the member variable of the newly created instance, which is called a shallow copy.

Deep copy: When a copy of a class is constructed, the value of all non-reference member variables of the object is not only copied, but also a new instance is created for the member variable of the reference type and initialized to the formal parameter instance value. This method is called deep copy

This means that a shallow copy copies only one object, passes a reference, and cannot replicate an instance. A deep copy copies the references inside the object, creates a new instance, and copies the instance.

For a shallow copy when the member variable of an object is the base data type, the member variable of two objects already has storage space, the assignment operation passes the value , so a shallow copy can replicate the instance. However, when the object's member variable is a reference data type , the object's replication cannot be implemented.

There is an object person with the following code:

public class Person {    private String name;    Private String sex;    private int age;        Public person (String name,string sex,int age) {        this.name = name;        This.sex = sex;        This.age = age;    }        Public person (person p) {                   //Copy construction method, copy object        this.name = p.name;        This.sex = P.sex;        This.age = P.age;    }}

The above object person has three member variables. Name, sex, age. Two methods of construction. The second parameter is the object, which is called the copy construction method, which initializes the new object created to the instance value of the formal parameter, which enables the object replication functionality.

There is also an object Asian, as follows:

public class Asian {    private String skin;    person person;        Public Asian (String skin,person person) {        This.skin = skin;        This.person = person;                    Reference Assignment    } public    Asian (Asian Asian) {                 //Copy construction method, copy Object this        (Asian.skin,asian.person);               }}

The above object also has two member variables, skin and person objects

For the person object there are the following:

person P1 = new Person ("John Doe", "Mam", 23); person P2 = new person (P1);

When the above statement is called. The P2 object will replicate to the P1. The implementation is as follows:

For Asian objects are:

Asian A1 = new Asian ("Yellow", New person ("John Doe", "Mam", 23)); Asian A2 = new Asian (A1);

New Asian (A1) executes the copy construction method of the Asian class, since the object assignment is a reference assignment. Enables A1 and A2 to reference the same object

Such as:

When A1 executes a statement that can change the value, A1 will also change the member variable of the A2 object through this statement

If you execute the following statement:a2.name = new Person (a1.name)

A new person object will be created.

Such as:

Http://www.cnblogs.com/chenssy/p/3308489.html

Simple analysis of Java's shallow copy and 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.