Deep cloning and shallow cloning of Java

Source: Internet
Author: User

Basic data types and reference data types for 1.Java

Basic data types include objects created by byte, int, char, long, float, double, Boolean, and short eight basic data types in the Java Virtual machine stack,

A reference data type creates an object that creates two objects, one in the stack, typically referred to as ' reference ', and the other in the Java heap.

2. Shallow cloning and deep cloning

The outward manifestation of a shallow clone is that the object is of the same underlying type object, referencing the same object, including the object stored in the heap. This means that all references to other objects still point to the original object.

The external manifestation of deep cloning is that the objects before and after the copy are equal, that is, the referenced objects are equal, not the memory in the same block of Java heap.

The same and equal are sufficient and not necessary for the object, the same must be equal, and the equivalence is often different.

A shallow clone is a copy that occurs in a stack, and a deep clone includes a copy of the reference object of the object in the heap.

Research on clone of 3.Java object

<span style= "Font-family:courier New;" >package Com.dusk.bean;public class Student implements Cloneable{private String id;private Address address;public Student () {}public Student (String id) {;} Public String GetId () {return ID;} Public Address getaddress () {return address;} public void setaddress (address address) {this.address = address;} @Overridepublic String toString () {return "Student [id=" + ID + "]";} public void SayHello () {System.out.println ("hello,everyone!");} @Overridepublic Student Clone () throws Clonenotsupportedexception {return (Student) Super.clone ();}} </span>

<span style= "Font-family:courier New;" >package Com.dusk.bean;public class Address {<span style= "White-space:pre" ></span>private String Address;<span style= "White-space:pre" ></span>public String getaddress () {<span style= "White-space: Pre "></span>return address;<span style=" White-space:pre "></span>}<span style=" White-space :p re "></span>public void Setaddress (String address) {<span style=" White-space:pre "></span> this.address = Address;<span style= "White-space:pre" ></span>}</span>

<span style= "Font-family:courier New;" >package com.dusk;import Org.junit.test;import Com.dusk.bean.student;public class Client {@Testpublic void Test () Throws Exception {Student stu1=new Student ("1"); Student Stu2=stu1.clone (); System.out.println (STU1==STU2); System.out.println (Stu1.getaddress () ==stu2.getaddress ());}} </span>
Operation Result:

<span style= "Font-family:courier New;" >falsetrue</span>

Conclusion: The Clone method provided by object is by default a shallow clone operation, and the address in the student object is not clone.

4. Verify the system.arraycopy with the same code:

<span style= "Font-family:courier New;" >package com.dusk;import Org.junit.test;import Com.dusk.bean.student;public class Test5 {@Testpublic void Test () { Student[] arr1=new student[]{new Student ("1"), New Student ("2"), New Student ("3"), New Student ("4")}; Student[] Arr2=new student[4]; System.arraycopy (arr1, 0, arr2, 0, 4); for (int i=0;i<arr2.length;i++) {System.out.println (arr1[i]==arr2[i]);}}} </span>
Operation Result:

<span style= "Font-family:courier New;" >truetruetruetrue</span>

found thatSystem.arraycopy provided also a shallow clone.

What if I implement deep clones? The answer is to rewrite the Clone method yourself.

For example:

<span style= "Font-family:courier New;" ><span style= "White-space:pre" ></span> @Overridepublic Student Clone () throws clonenotsupportedexception {Student stu=new Student (); Stu.setid (; Stu.setaddress (new Address ()); return Stu;} </span>
The result must be:

<span style= "Font-family:courier New;" >falsefalse</span>
Is that it? How could it be,

What if we had the address cloneable? became

<span style= "Font-family:courier New;" >package Com.dusk.bean;public class Address implements cloneable{@Overrideprotected Object clone () throws clonenotsupportedexception {//TODO auto-generated method Stubreturn Super.clone ();}} </span>
continue calling the scenario in 3, and the result is:

<span style= "Font-family:courier New;" >falsetrue</span>
altogether is not my intended recursive call, it seems that if their object reference deep in the case of deep cloning, self-can withdraw their own bitter fruit.

Is that all you can do?

See I will kill skill, ObjectOutputStream and ObjectInputStream, sacrifice magic Weapon:

<span style= "Font-family:courier New;" >package Com.dusk;import;import;import;import;import Org.junit.test;import com.dusk.bean.Address; Import Com.dusk.bean.student;public class client{@Testpublic void Test () throws Clonenotsupportedexception {Student Stu1=new Student ("1"); Address add = new address (); stu1.setaddress (add); Student stu2= (Student) deepcopy (STU1); System.out.println (STU1==STU2); System.out.println (Stu1.getaddress () ==stu2.getaddress ());}  Private object Deepcopy (Object obj) {//Writes the object to the stream in try {bytearrayoutputstream bo=new bytearrayoutputstream (); ObjectOutputStream Oo;oo = new ObjectOutputStream (bo);  Oo.writeobject (obj);  Read it out of the stream Bytearrayinputstream bi=new Bytearrayinputstream (Bo.tobytearray ());  ObjectInputStream oi=new ObjectInputStream (BI); Return (Oi.readobject ()); } catch (Exception e) {e.printstacktrace ();} return obj;}} </span>


<span style= "Font-family:courier New;" >falsefalse</span>

a perfect solution to the problem of deep cloning of object multi-apply.

As long as the thought does not slide, the way is always more difficult!

Deep cloning and shallow cloning of Java

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.