Java two methods to achieve deep copy of the object

Java two methods to achieve deep copy of the object

Disclaimer: This article is a blogger original article, follow the  CC 4.0 BY-SA  copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/caoxiaohong1005/article/details/78704890

 

1, if a class does not implement the Cloneable interface direct call clone () method, will be reported abnormal CloneNotSupportedException, I already wrote in Object source code:

 

  1.  
    * @return a clone of this instance.
  2.  
    * @exception CloneNotSupportedException if the object's class does not
  3.  
    * support the {@code Cloneable} interface. Subclasses
  4.  
    * that override the {@code clone} method can also
  5.  
    * throw this exception to indicate that an instance cannot
  6.  
    * be cloned.
  7.  
    * @see java.lang.Cloneable
  8.  
    */
  9.  
    protected native Object clone() throws CloneNotSupportedException;

 
  

 

 
  

 

Moreover, the source code is also written to the clone Object () method is a shallow copy, which is in Object source code analysis before I have written a.

 
  

2, a custom class that implements the deep copy method has two kinds, specific wording given below sequentially.

2.1, custom class to implement the Cloneable interface and override clone () method.

 

 

  1.  
    /**
  2.  
    * Deep copy and shallow copy of testing
  3.  
    */
  4.  
    // Test category 1
  5.  
    class Person implements Cloneable{
  6.  
    String name;
  7.  
    int age;
  8.  
    Person(String name, int age){
  9.  
    this.name=name;
  10.  
    this.age=age;
  11.  
    }
  12.  
    @Override
  13.  
    public Object clone() {
  14.  
    try{
  15.  
    return super.clone();
  16.  
    } catch(CloneNotSupportedException e){
  17.  
    return null;
  18.  
    }
  19.  
    }
  20.  
    }
  21.  
    // test class 2
  22.  
     
  23.  
    class Animal implements Cloneable{
  24.  
    Host the Person; // owner
  25.  
    Age int; // old
  26.  
    Animal(Person person, int age){
  27.  
    this.host=person;
  28.  
    this.age=age;
  29.  
    }
  30.  
    @Override
  31.  
    public Object clone(){
  32.  
    try{
  33.  
    Animal animal=(Animal) super.clone();
  34.  
    = animal.host (the Person) host.clone (); // process a deep copy
  35.  
    return animal;
  36.  
    } catch (CloneNotSupportedException e){
  37.  
    return null;
  38.  
    }
  39.  
    }
  40.  
    }
  41.  
     
  42.  
    //test
  43.  
    public class Main{
  44.  
    public static void main(String[] args) {
  45.  
    Person person1= new Person("cxh",26);
  46.  
    Person person2=(Person)person1.clone();
  47.  
    System.out.println ( "shallow copy ---------------- --------------");
  48.  
    // Object clone method for testing shallow copy
  49.  
    // String class == test is consistent with the memory address
  50.  
    System.out.println ( "PERSON1 person2 and the same memory address name:" + (person1.name == person2.name) );
  51.  
     
  52.  
     
  53.  
     
  54.  
    System.out.println ( "---------------- -------------- deep copy");
  55.  
    // override the clone method of Object, achieve deep copy
  56.  
    // or use == to see two objects are equal memory address to determine whether the two objects, and if two memory addresses, then that is a deep copy
  57.  
    Animal animal1= new Animal(new Person("cxh",26),3);
  58.  
    Animal animal2=(Animal) animal1.clone();
  59.  
    System.out.println ( "animal1 animal2 the host and the same memory address:" + (animal1.host == animal2.host) );
  60.  
    }
  61.  
    }

Output:
 
  

 

 

 

  1.  
    ---------------- -------------- shallow copy
  2.  
    person1 and person2 the name memory address is the same: to true
  3.  
    ---------------- -------------- deep copy
  4.  
    animal1 and animal2 the host memory address is the same: false
  5.  
     
  6.  
    Process finished with exit code 0

 

A very detailed explanation of the blog: http://blog.csdn.net/zhangjg_blog/article/details/18369201


 
  

 

2.2, is achieved by way of a deep copy of the sequence: first to copy the object is written to the byte stream in the memory, and then reads the byte stream from the information stored just as a new object is returned, then the new object and share original object does not exist on any address, to achieve a natural deep copy.

Custom class needs to implement Serializable interface.

 

  1.  
    import java.io. *;
  2.  
     
  3.  
    /**
  4.  
    * Deep copy and shallow copy of testing
  5.  
    * How to use serialized copy of the object to complete it? Copies of the byte stream is relatively easy to implement in memory through. The parent object is written to a byte stream, then it will read from the byte stream,
  6.  
    * This will create a new object, and there is no reference and sharing issues between the new object and parent objects, a deep copy of the real object.
  7.  
    */
  8.  
    //Tools
  9.  
    class CloneUtil{
  10.  
    public static <T extends Serializable> T clone(T obj){
  11.  
    T cloneObj= null;
  12.  
    try{
  13.  
    // write byte stream
  14.  
    ByteArrayOutputStream baos= new ByteArrayOutputStream();
  15.  
    ObjectOutputStream oos= new ObjectOutputStream(baos);
  16.  
    oos.writeObject (obj);
  17.  
    oos.close ();
  18.  
     
  19.  
    // allocate memory, write the original object, generate a new object
  20.  
    Bais = A ByteArrayInputStream new new A ByteArrayInputStream (baos.toByteArray ()); // Get the above output byte stream
  21.  
    ObjectInputStream ois= new ObjectInputStream(bais);
  22.  
     
  23.  
    // returns a new object generated
  24.  
    cloneObj=(T)ois.readObject();
  25.  
    ois.close();
  26.  
    } catch (Exception e){
  27.  
    e.printStackTrace ();
  28.  
    }
  29.  
    return cloneObj;
  30.  
    }
  31.  
    }
  32.  
     
  33.  
    // Test category 1
  34.  
    class Person implements Serializable{
  35.  
    String name;
  36.  
    int age;
  37.  
    Person(String name, int age){
  38.  
    this.name=name;
  39.  
    this.age=age;
  40.  
    }
  41.  
     
  42.  
    }
  43.  
    // test class 2
  44.  
     
  45.  
    class Animal implements Serializable{
  46.  
    Host the Person; // owner
  47.  
    Age int; // old
  48.  
    Animal(Person person, int age){
  49.  
    this.host=person;
  50.  
    this.age=age;
  51.  
    }
  52.  
    }
  53.  
     
  54.  
     
  55.  
    //test
  56.  
    public class Main{
  57.  
    public static void main(String[] args) {
  58.  
    System.out.println ( "---------------- -------------- deep copy");
  59.  
    // override the clone method of Object, achieve deep copy
  60.  
    // or use == to see two objects are equal memory address to determine whether the two objects, and if two memory addresses, then that is a deep copy
  61.  
    Animal animal1= new Animal(new Person("cxh",26),3);
  62.  
    Animal animal2=CloneUtil.clone(animal1);
  63.  
    System.out.println ( "animal1 animal2 the host and the same memory address:" + (animal1.host == animal2.host) );
  64.  
    }
  65.  
    }

Output:

 

 

  1.  
    ---------------- -------------- deep copy
  2.  
    animal1 and animal2 the host memory address is the same: false

Reference blog: http://blog.csdn.net/chenssy/article/details/12952063

Guess you like

Origin www.cnblogs.com/think90/p/11440153.html