Shallow clone (Shallow clone) and deep clone in Java

Source: Internet
Author: User


Shallow cloning and deep cloning is a low-difficulty factor for javase, but should not be underestimated.

Suppose a scenario: for a list, there is no direct manipulation of it in the code, but the attributes of the elements inside are changed, which may involve this concept.


shallow cloning refers to a reference (reference) that only the Copy object is in the stack memory. After copy, both the old and new references point to the same heap memory object (that is, the same memory region), but there is only one before and after the actual object copy in the heap memory. Use the "= =" operator to compare the addresses of the two to return true. (Different references, same object)

A deep clone refers to the copy of a new object and returns the corresponding reference, which opens up new heap memory space, thus returning false when using the "= =" operator to compare the addresses of the two. (Different references, different objects)

Shallow clone (Shallow clone)

    1. When the Clone object is an instance object, use the "=" operator for shallow cloning.
    2. When a clone object is an element of an object array, it is used System.arraycoppy() for shallow cloning. (You have to use the "=" foreach clone and no one to stop it.)

The clone operations explicitly defined in the JDK are basically used:

1 int int int length)

For example, Clone (), arrays.copyof (), and so on for a specific array in ArrayList are actually called by the bottom of the method.

1  PackageCom.scv.test.clone;2 3  Public classShallowclonetest {4 5      Public Static voidMain (string[] args)throwsException {6Zerg z0 =NewZerg ();7Zerg Z1 =z0;8System.out.println ("0." + (Z0 = = z1));//"=" operator for shallow cloning of objects9         Tenzerg[] Array0 =Newzerg[]{NewZerg (),NewZerg ()}; Onezerg[] Array1 =NewZerg[array0.length]; ASystem.arraycopy (array0, 0, array1, 0, array0.length);//system.arraycopy () for shallow cloning of arrays -System.out.println ("1." + (Array0 = =array1)); -          for(inti = 0; i < array0.length; i++){ theSYSTEM.OUT.PRINTLN ("Comparing element of array:" + (array0[i] = =array1[i])); -         } -     } -      + } -  + classzerg{ A      at } -  - /*Output: - 0. True - 1. False - comparing element of Array:true in comparing element of Array:true - */
Verify Shallow Clone

Deep clone

The JDK does not show a definition deep clone, or does not provide a tool class directly. To allow your custom class to support deep cloning, you must have two conditions:

    1. Implements Cloneable interface.
    2. Override Clone () defined in Java.lang.Object.

If you do not implement cloneable and override the Clone () of the object directly, the Clonenotsupportedexception is thrown.

1  PackageCom.scv.test.clone;2 3  Public classDeepclonetest {4 5      Public Static voidMain (string[] args)throwsException {6Cloneablezerg z0 =NewCloneablezerg ();7Cloneablezerg Z1 =Z0.clone ();8         9System.out.println ("0." + (Z0 = =z1));Ten     } One      A } -  - classCloneablezergImplementscloneable{ the      - @Override -      PublicCloneablezerg Clone ()throwsclonenotsupportedexception{ -         return(Cloneablezerg)Super. Clone (); +     } - } +  A /*Output: at 0. False - */
Verify Deep Clone

In fact, you can customize which member variables (field) Allow clone, which is not allowed (a little transient feeling?). )。  

Implementation in JDK: Shallow clone and deep clone in ArrayList

1  PackageCom.scv.test.clone;2 3 Importjava.util.ArrayList;4 5  Public classArraylistclonetest {6 7      Public Static voidMain (string[] args)throwsException {8Clonetarget T =Newclonetarget ();9         TenArraylist<clonetarget> list0 =NewArraylist<clonetarget> (1); One List0.add (t); AArraylist<clonetarget> List1 = (arraylist<clonetarget>) List0.clone (); -List0.get (0). Setfielda (20); -          theSystem.out.println ("0." + (List0 = =list1)); -System.out.println ("1." + (list0.get (0) = = List1.get (0))); -System.out.println ("2." + list1.get (0). Getfielda ()); -     } +      - } +  A classClonetargetImplementscloneable{ at      -     Private intFielda = 10; -      - @Override -      PublicClonetarget Clone ()throwsclonenotsupportedexception{ -         return(Clonetarget)Super. Clone (); in     } -      to      Public voidSetfielda (inta) { +Fielda =A; -     } the      *      Public intGetfielda () { $         returnFielda;Panax Notoginseng     } - } the  + /* A * Output: the * 0. False + * 1. True - * 2. $ */
Click Me

Operating instructions:

    1. Create a ArrayList object List0
    2. Add an object to the List0 t
    3. Clone List0 object is List1
    4. To modify the properties of an element (that is, T) in List0

Result Description:

    1. ArrayList implements the Cloneable interface, Arraylist.clone () is a deep clone, so list0 and List1 point to different memory areas respectively.
    2. The Clone () of the ArrayList object is a shallow clone of the inner array, so the element in List0 (t) is the same as the element in List1, and the modification of the LIST0 element affects the List1 element.

Shallow clone (Shallow clone) and deep clone in Java

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: 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.