java-deep cloning and shallow cloning

Source: Internet
Author: User
Tags object serialization serialization

Article Reference https://www.cnblogs.com/acode/p/6306887.html

First, the premise

1. The class using the Clone () method must implement the Cloneable interface,

Otherwise, when the Clone () method is called, the clonenotsupportedexception is thrown

2, Clone () is the protected modifier method, so if you want to use the Clone () method, you must implement it in the subclass

Second, actual combat

Class Relationships (

Student: two base type properties

A reference type property)

1. Create a Student class

@Data
public class Student implements Cloneable{

private String name;

private int age;

Private mother mother;

@Override
Protected Object Clone () throws Clonenotsupportedexception {
Student Student = (Student) super.clone ();
try {
Mother Mother1 = (mother) Mother.clone ();
Student.setmother (Mother1);
} catch (Exception e) {
E.printstacktrace ();
}
return student;
}
}

2. Create a Mother class

@Data  Public class Implements cloneable {    private  String name;     Private int Age ;        @Override    protectedthrows  clonenotsupportedexception {          ReturnSuper. Clone ();}    }

3. Create a test class

public class Test {

public static void Main (string[] args) throws Exception {
============ Initialize ================
Mother mother = new mother ();
Mother.setname ("Xiao Wang Mama");
Mother.setage (40);
Student Student = new Student ();
Student.setage (1);
Student.setname ("Xiao Wang");
Student.setmother (mother);
============ Cloning ================
Student Student2 = (Student) student.clone ();
Student2.setname ("Xiao Li");
Student2.setage (2);
Student2.getmother (). Setage (45);
Student2.getmother (). SetName ("Xiao Li Mama");
============ Output ================
SYSTEM.OUT.PRINTLN (student);
System.out.println (Student2);
}
}

Iii. Results

Student (name= Xiao Wang, age=1, Mother=mother (name= Xiao Wang Mama, age=40))
Student (Name= Xiao Li, age=2, Mother=mother (name= Xiao Li Mama, age=45))

Iv. Analysis

1, the results of the implementation of deep-class cloning

2, if not in the Clone () method of the student class, the operation of the Mother class, then the Mother property will only refer to the operation

Modify the Clone () method in the Student class

@Override     protected throws clonenotsupportedexception {        returnSuper. Clone ();    }

Results

Student (name= Xiao Wang, age=1, Mother=mother (name= Xiao Li Mama, age=45)) Student (name= Xiao Li, age=2, Mother=mother (name= Xiao Li Mama, age=45))

3, Crooked door Evil (to achieve serialization interface, to achieve clone) object serialization, but serialization is very time-consuming, in some frameworks, we can feel that they tend to serialize the object after the transfer, time-consuming.

@Data Public classStudentImplementsserializable{Private Static Final LongSerialversionuid = 1L; PrivateString name; Private intAge ; Privatemother mother;  PublicObject Deepclone ()throwsIOException, ClassNotFoundException {//write an object into the streamBytearrayoutputstream 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 ()); }}
@Data  Public class Implements Serializable {    privatestaticfinallong serialversionuid = 1L;     Private  String name;     Private int Age ;    }

Result: Deep cloning succeeded

Student (name= Xiao Wang, age=1, Mother=mother (name= Xiao Wang Mama, age=40)) Student (name= Xiao Li, age=2, Mother=mother (name= Xiao Li Mama, age=45))

java-deep cloning and shallow cloning

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.