Java deep copy and shallow copy

Source: Internet
Author: User
Tags shallow copy

1. Concept

The clone in Java is divided into:
A: Shallow copy (Shallow clone): Shallow copy copies only the objects that you are considering, not the objects that it refers to.
B: Deep copy (Deep clone): Deep copy copies the objects referenced by the object to be copied again.
Cloning of objects in Java, in order to get a copy of the object, we can take advantage of the object class's Clone () method. Have to follow the three points below
1. Override the Clone () method of the base class in the derived class and declare it as public "the Clone () method in the object class is protected".
2. In the Clone () method of the derived class, call Super.clone ().
3. Implement the Cloneable interface in a derived class.

Note: The Clone method in the object class is shallow copy (shallow clone)

2. The Clone () method of Java

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 ()//Clone the object as the type of the original object
③ if the Equals () method of object x is defined properly, then X.clone (). Equals (x) should be established.

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.

Take a look at the following code:

public class Student implements cloneable{String name;    int age;        Student (String Name,int age) {this.name=name;    This.age=age;        } public Object Clone () {object o=null;         try {o= (Student) Super.clone (); Clone () in//object identifies which object you want to copy.        } catch (Clonenotsupportedexception e) {System.out.println (e.tostring ());    } return o;        } public static void Main (string[] args) {Student s1=new Student ("Zhangsan", 18);        Student s2= (Student) S1.clone ();        S2.name= "Lisi";        s2.age=20;        After the Student 2 is modified, the student's 1 value is not affected.        System.out.println ("Name=" +s1.name+ "," + "age=" +s1.age);    System.out.println ("Name=" +s2.name+ "," + "age=" +s2.age); }} 

Description:  
① Why do we have to call Super.clone () when we overwrite the Clone () method of object in a derived class? At run time, Clone () in object identifies which object you want to copy, then allocates space for the object, replicates the object, and copies the contents of the original object one by one into the storage space of the new object.  
② inherits from the Java.lang.Object class's Clone () method is shallow copy. The following code can prove it.

Class Professor implements cloneable{String name;    int age;        Professor (String Name,int age) {this.name=name;    This.age=age;        } public Object Clone () {object o=null;        try {o=super.clone ();        } catch (Clonenotsupportedexception e) {System.out.println (e.tostring ());    } return o;    }}public class Student implements cloneable{String name;    int age;    Professor P;        Student (String name,int age,professor p) {this.name=name;        This.age=age;    This.p=p;        } public Object Clone () {Student o=null;        try {o= (Student) Super.clone ();        } catch (Clonenotsupportedexception e) {System.out.println (e.tostring ());        }//To the referenced object is also replicated o.p= (professor) P.clone ();    return o;        } public static void Main (string[] args) {Professor P=new professor ("Wangwu", 50); StudeNT S1=new Student ("Zhangsan", 18,p);        Student s2= (Student) S1.clone ();        S2.p.name= "Lisi";        s2.p.age=30;        1 of the professors of the students do not change.        System.out.println ("Name=" +s1.p.name+ "," + "age=" +s1.p.age);    System.out.println ("Name=" +s2.p.name+ "," + "age=" +s2.p.age);  }}

How should a deep-seated clone be implemented, that the professor who modifies S2 will not affect S1 's professors? The code is improved as follows.  
Improvements make the professor of 1 students unchanged (deep cloning)

public class Student implements cloneable{String name;    int age;    Professor P;        Student (String name,int age,professor p) {this.name=name;        This.age=age;    This.p=p;        } public Object Clone () {Student o=null;        try {o= (Student) Super.clone ();        } catch (Clonenotsupportedexception e) {System.out.println (e.tostring ());        }//To the referenced object is also replicated o.p= (professor) P.clone ();    return o;        } public static void Main (string[] args) {Professor P=new professor ("Wangwu", 50);        Student s1=new Student ("Zhangsan", 18,p);        Student s2= (Student) S1.clone ();        S2.p.name= "Lisi";        s2.p.age=30;        1 of the professors of the students do not change.        System.out.println ("Name=" +s1.p.name+ "," + "age=" +s1.p.age);    System.out.println ("Name=" +s2.p.name+ "," + "age=" +s2.p.age); }} 

  3. Use serialization to do deep replication (mainly to avoid rewriting the clone () method that compares the deep copy of a complex object, or to implement a program to resume a breakpoint, etc.)
The process of writing objects into a stream is a serialization (serilization) process, but is also very visually called "Frozen" or "pickled pickles (picking)" In the Java programming community. The parallelization (deserialization) process, which reads objects from the stream, is called a "thaw" or "depicking" process.
It should be noted that the write in the stream is a copy of the object, and the original object is still in the JVM, so "pickle" is only a copy of the object, Java Pickles can also be returned fresh.
In the Java language, a deep copy of an object can often be used to implement the Serializable interface, and then the object (actually a copy of the object) is written into a stream (pickled pickles), and then read out from the stream (pickles back fresh), you can reconstruct the object.
The following is a deep copy of the source code.

     PublicObject Deepclone () {//write an object into the streamBytearrayoutoutstream bo=NewBytearrayoutputstream (); ObjectOutputStream oo=NewObjectOutputStream (bo); Oo.writeobject ( This); //read it from the stream.Bytearrayinputstream bi=NewBytearrayinputstream (Bo.tobytearray ()); ObjectInputStream Oi=NewObjectInputStream (BI); return(Oi.readobject ()); } 

This is done only if the object and all objects referenced inside the object are serializable, otherwise it is necessary to examine carefully those objects or attributes that are not serializable to be transient, thereby excluding them from the replication process. The above example code is improved as follows.

Class Teacher implements Serializable {String name;    int age;        public void Teacher (String name,int age) {this.name=name;    This.age=age;    }}public class Student implements serializable{String name;//constant object int age;    Teacher t;//The reference value for student 1 and Student 2 is the same.        public void Student (String name,int age,teacher t) {this.name=name;        This.age=age;    This.p=p;        } public Object Deepclone () throws IOException, optionaldataexception,classnotfoundexception{//writes the object to the stream        Bytearrayoutoutstream bo=new Bytearrayoutputstream ();        ObjectOutputStream oo=new ObjectOutputStream (bo);        Oo.writeobject (this);//read out from the stream bytearrayinputstream bi=new Bytearrayinputstream (Bo.tobytearray ());        ObjectInputStream oi=new ObjectInputStream (BI);    Return (Oi.readobject ());        } public static void Main (string[] args) {Teacher t=new Teacher ("Tangliang", 30);        Student s1=new Student ("Zhangsan", 18,t); Student s2= (Student) s1.Deepclone ();        S2.t.name= "Tony";        s2.t.age=40;    The teacher of the student 1 does not change System.out.println ("Name=" +s1.t.name+ "," + "age=" +s1.t.age); }}

Reference: http://www.jb51.net/article/62909.html

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