Clone () deep copy shallow copy in Java

Source: Internet
Author: User
Tags shallow copy

Shows a shallow copy: for non-basic data types, after clone, the result is two pointers pointing to the same memory space, so it is only a shallow copy, so if the operation on one object, the other content will also change, it is obviously unreasonable, should each object to save their own data.

So we're going to make a deep copy!

Shallow copy and deep copy examples:

Import Java.util.vector;public class Student implements Cloneable{private int id;private String name;private Vector Cours Es;public Student () {try{thread.sleep (1000); System.out.println ("Student construnctor called");} catch (Interruptedexception e) {e.printstacktrace ();}} public int getId () {return ID;} public void setId (int id) {this.id=id;} Public String GetName () {return name;} public void SetName (String name) {this.name=name;} Public Vector getcourses () {return courses;} public void setcourses (Vector courses) {this.courses=courses;} Public Student newinstance () {//Use Clone () to create object, shallow copy Try{return (Student) This.clone ();} catch (Clonenotsupportedexception e) {e.printstacktrace ();} return null;} Public Student Deepclone () {//Uses clone () to create the object, deep copy try{student cloning = (Student) super.clone ();//student cloning = ( strdent) This.clone ();//And the previous sentence effect equivalent cloning.courses = new Vector ();//Key: The non-basic data type of space needs to be newly opened together return cloning;} catch (Clonenotsupportedexception e) {e.printstacktrace ();} return null;}}
Import Java.util.vector;public class Test {public static void main (string[] args) {//TODO auto-generated method Stubstude NT STU1 = Null;shallowcopydemo (STU1); SYSTEM.OUT.PRINTLN ("---------------I ' m cut-off rule---------------");d Eepcopydemo (STU1);} public static void Shallowcopydemo (Student stu1) {stu1=new Student (); Vector cs=new vector (); Cs.add ("Java"); Stu1.setid (1); Stu1.setname ("Tom"); Stu1.setcourses (CS); Student stu2=stu1.newinstance (); Stu2.setid (2); Stu2.setname ("Mary"); Stu2.getcourses (). Add ("C #"); System.out.println ("STU1 ' Name:" +stu1.getname ()); System.out.println ("STU2 ' Name:" +stu2.getname ()); System.out.println (Stu1.getcourses () ==stu2.getcourses ()); System.out.println (Stu1.getname + "s course:" + stu1.getcourses ()); System.out.println (Stu2.getname + "s course:" + stu2.getcourses ());} public static void Deepcopydemo (Student stu1) {stu1=new Student (); Vector cs=new vector (); Cs.add ("Java"); Stu1.setid (1); Stu1.setname ("Tom"); Stu1.setcourses (CS); Student Stu2=stu1.deepclone (); Stu2.setid (2); Stu2.setname ("Mary"); Stu2.getcourses (). Add ("C #"); System.out.println ("STU1 ' Name:" +stu1.getname ()); System.out.println ("STU2 ' Name:" +stu2.getname ()); System.out.println (Stu1.getcourses () ==stu2.getcourses ()); System.out.println (Stu1.getname + "s course:" + stu1.getcourses ()); System.out.println (Stu2.getname + "s course:" + stu2.getcourses ());}}


Output Result:


Student Construnctor called
STU1 ' Name:tom
Stu2 ' Name:mary
True
Tom ' s course: [Java, C #]
Mary ' s course: [Java, C #]
---------------I ' m cut-off rule---------------
Student Construnctor called
STU1 ' Name:tom
Stu2 ' Name:mary
False
Tom ' s course: [Java]
Mary ' s course: [C #]

As the result shows, the first call to a shallow copy causes the Class C # to be added to Mary, and Tom's course also has C #, and Mary's course also has Tom's Java, and Stu1.getcourses () ==stu2.getcourses () returns " True ", stating that the course property of both points to the same memory, whereas in the second case we open up a new space for the copy-out Mary's course cloning.courses So Tom and Mary manipulate different vector memory, and the two naturally differ.


In the above example, the deep copy Deepclone () and the shallow copy newinstance () functions were written by ourselves, so Deepclone () Student cloning = (Student) super.clone () and Student cloning = (strdent) This.clone () is feasible. In addition, we can also directly overwrite the clone () function of the class so that we can only use Student cloning = (Student) super.clone () , the code to overwrite is as follows:

Public Object Clone () {//Overwrite clone (), deep copy try{student cloning = (Student) super.clone (); cloning.courses = new Vector ();// Key point: The non-basic data type of space needs its own new opening together return cloning;} catch (Clonenotsupportedexception e) {e.printstacktrace ();} return null;}
You can't use it here.the reason for Student cloning = (strdent) This.clone () is that we are repeating the Clone () method of the class, and if we call the function of this class again, that is: This.clone (), it is equivalent to the wireless recursive infinite dead loop. , and it will surely crumble in the end. So here we can only invoke the function of the parent class, namely: Super.clone ().

So, either you give yourself a name for your deep copy function , or you can overwrite the Clone () method of the class, choose one yourself, but the key is to re-join the new space for non-basic data types.

Clone () deep copy shallow copy 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: 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.