Deep copy of objects in Java (deep cloning) and shallow replication (shallow cloning) Introduction _java

Source: Internet
Author: User
Tags shallow copy

1. Shallow copy and deep copy Concepts

⑴ Shallow copy (shallow clone)  

    All variables of a replicated object contain the same value as the original object , and all references to other objects still point to the original object. In other words, a shallow copy replicates only the object being considered, not the object it references.

⑵ deep copy (Deep clone)  

    All variables of a replicated object contain the same values as the original object, excluding those that refer to other objects. The variables that refer to other objects will point to the new object that was copied, not the original referenced object. In other words, deep copy copies the objects that are referenced by the object being copied.

2. The Java Clone () method

⑴clone method copies an object and returns it to the caller. In general, the Clone () method satisfies:
① for any object x, there is a x.clone ()!=x//The Clone object is not the same object as the original object
② to any object x, X.clone (). GetClass () = = X.getclass ()//The Clone object is the same as the type of the original object
③ if the Equals () method of object x is properly defined, then X.clone (). Equals (x) should be set up.

cloning of objects in ⑵java

① in order to get a copy of the object, we can take advantage of the Clone () method of the Class object. The
② overrides the Clone () method of the base class in a derived class and is declared public. The
③ calls Super.clone () in the Clone () method of the derived class. The
④ implements the Cloneable interface in a derived class.

See 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 are copying. 
   } 
  catch (clonenotsupportedexception e) 
   { 
    System.out.println (e.tostring ()); 
   } 
  return o; 
  }  
 
 public static void Main (string[] args) 
  { 
  Student s1=new Student ("Zhangsan"); 
  Student s2= (Student) S1.clone (); 
  S2.name= "Lisi"; 
  s2.age=20; 
  After modifying student 2, the value of student 1 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 override the object's clone () method in a derived class? At run time, the Clone () in object identifies which object you want to replicate, then allocates space for the object, replicates the object, and copies the original object's content one by one to the new object's storage space.
the Clone () method ② inherits from the Java.lang.Object class is a shallow copy. The following code can prove it.

 class Professor {String name; 
  int age; 
  Professor (String Name,int age) {this.name=name; 
  This.age=age; 
  The public class Student implements cloneable {String name;//constant object. 
  int age; 
  The reference values for Professor p;//1 and Student 2 are the same. 
  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 ()); 
  } 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;
  System.out.println ("Name=" +s1.p.name+ "," + "age=" +s1.p.age);
  System.out.println ("Name=" +s2.p.name+ "," + "age=" +s2.p.age);
  The output of the students 1 and 2 of the professors became lisi,age to 30. } 
} 

How should a deep cloning be achieved, that is, the professor who modifies S2 does not affect S1 's professors? Code improvements are as follows.
Improve the professor of Student 1 (deep cloning)

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 ()); 
  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;
  Students 1 of the professors 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 (primarily to avoid rewriting the clone () method of deep replication for complex objects, or to implement a breakpoint continuation, etc.)
The process of writing an object into a stream is a serialized (serilization) process, but in the Java programming community it is very vividly known as the "Frozen" or "pickled pickle (picking)" process While the parallelization (deserialization) process of reading objects from the stream is called "thaw" or "fresh (depicking)" process.
It should be noted that the written in the stream is a copy of the object, and the original object still exists in the JVM, so "pickled vegetables" is only a copy of the object, Java Pickles can also be fresh back.
Deep copying of an object in the Java language allows the object to be serializable, and then the object (actually just a copy of the object) is written into a stream (salted into a pickle), and then read from the stream (the pickle back to fresh), and the object can be rebuilt.
The following is the deep copy source code.

The public object Deepclone () 
{ 
 //writes the object to the stream 
 Bytearrayoutoutstream bo=new bytearrayoutputstream (); 
 ObjectOutputStream oo=new ObjectOutputStream (bo); 
 Oo.writeobject (this); 
 Read it out of the stream 
 bytearrayinputstream bi=new bytearrayinputstream (Bo.tobytearray ()); 
 ObjectInputStream oi=new ObjectInputStream (BI); 
 Return (Oi.readobject ()); 

The premise is that objects and all referenced objects within the object are serializable, otherwise, it is necessary to carefully examine those serializable objects or properties can be set to transient, so that it excluded from the replication process. The example code above 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;
 The public class Student implements serializable{String name;//constant object int age;
 The reference values for Teacher t;//1 and Student 2 are the same.
  public void Student (String name,int age,teacher t) {this.name=name;
  This.age=age;
 This.p=p; The public object Deepclone () throws IOException, optionaldataexception,classnotfoundexception{//writes objects to the stream bytearrayout
  OutStream bo=new Bytearrayoutputstream ();
  ObjectOutputStream oo=new ObjectOutputStream (bo);
  Oo.writeobject (this); read 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; Students 1 of the teacher does not change System.out.println ("Name=" +s1).T.name+ "," + "age=" +s1.t.age); }
}
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.