Java shallow and deep clone clone

Foreword

Clone, i.e., copy an object, the object attribute is consistent with the object to be copied, without using the clone method implemented in the class Object clone can be a new object itself, and the corresponding attribute data, so that cloning can be achieved the goal of.

But when more object properties, such clones would be more cumbersome manner, so the Object class implements clone method for cloning the object.

Java clone is divided into shallow and deep clone clone

First, to achieve cloning way

1. Object class need to implement the interface Cloneable

2. Object class override clone () method

3. () method to get the desired results according to clone rewritten clone, such as a shallow clone and a deep clone.

Difference between the two, a shallow clone and a deep clone

Shallow Clone: ​​When copying only the object itself copying objects, including basic properties, but the properties of the other objects referenced object, the referenced object is not copied, i.e., out of the copy object referenced object out of the copied object properties It is the same.

Deep Cloning: A copy of the object itself, but also copy the object contains references to the object, i.e., any property modifications are cloned object will not affect the cloned target.

Test Case 1:

 1 public class Person implements Cloneable{
 2     private int age;
 3     private String name;
 4 
 5     public Person(int age, String name) {
 6         this.age = age;
 7         this.name = name;
 8     }
 9 
10     public int getAge() {
11         return age;
12     }
13 
14     public void setAge(int age) {
15         this.age = age;
16     }
17 
18     public String getName() {
19         return name;
20     }
21 
22     public void setName(String name) {
23         this.name = name;
24     }
25 
26     @Override
27     public String toString() {
28         return "Person{" +
29                 "age=" + age +
30                 ", name='" + name + '\'' +
31                 '}';
32     }
33 
34     @Override
35     protected Person clone() throws CloneNotSupportedException {
36         return (Person)super.clone(); //调用父类的clone方法
37     }
38 }
39 
40 public class CloneTest {
41 
42     public static void main(String[] args) throws CloneNotSupportedException {
43         Person person = new Person(22,"LiLei");
44         Person newPerson = person.clone();
45         person.setAge(21);
46         person.setName("HanMeimei");
47         System.out.println(person.toString());
48         System.out.println(newPerson.toString());
49     }
50 }

operation result:

I.e., after cloning a new object, modify the basic properties of the clone, and does not affect the object cloned. But when the object attribute is cloned reference other objects, at this time have different results.

Test Case 2:

 1 class Student implements Cloneable{
 2     private String name;
 3     private Achievement achievement; //成绩
 4 
 5     public Student(String name, Achievement achievement) {
 6         this.name = name;
 7         this.achievement = achievement;
 8     }
 9 
10     public void setName(String name) {
11         this.name = name;
12     }
13 
14     public void setAchievement(Achievement achievement) {
15         this.achievement = achievement;
16     }
17 
18     public Achievement getAchievement() {
19         return achievement;
20     }
21 
22     @Override
23     public String toString() {
24         return "Student{" +
25                 "name='" + name + '\'' +
26                 ", achievement=" + achievement +
27                 '}';
28     }
29 
30     @Override
31     protected Student clone() throws CloneNotSupportedException {
32         return (Student) super.clone();
33     }
34 }
35 
36 /**
37  * 成绩类
38  */
39 class Achievement implements Cloneable{
40     private float Chinese;
41     private float math;
42     private float English;
43 
44     public Achievement(float chinese, float math, float english) {
45         Chinese = chinese;
46         this.math = math;
47         English = english;
48     }
49 
50     public void setChinese(float chinese) {
51         Chinese = chinese;
52     }
53 
54     public void setMath(float math) {
55         this.math = math;
56     }
57 
58     public void setEnglish(float english) {
59         English = english;
60     }
61 
62     @Override
63     public String toString() {
64         return "Achievement{" +
65                 "Chinese=" + Chinese +
66                 ", math=" + math +
67                 ", English=" + English +
68                 '}';
69     }
70 
71     @Override
72     protected Achievement clone() throws CloneNotSupportedException {
73         return (Achievement) super.clone();
74     }
75 }
76 
77 
78 public class CloneTest {
79 
80     public static void main(String[] args) throws CloneNotSupportedException {
81         Achievement achievement = new Achievement(100,100,100);
82         Student student = new Student("LiLei",achievement);
83         // 克隆出一个对象
84         NewStudent = Student student.clone ();
 85  
86          // modify the original object properties 
87          student.setName ( "HanMeimei" );
 88          student.getAchievement () setChinese (90. );
 89          student.getAchievement () setEnglish (. 90 );
 90          student.getAchievement () setMath (90. );
 91 is  
92          System.out.println (newStudent);
 93          System.out.println (Student);
 94      }
 95 }

operation result:

The above phenomenon indicates that the clone mode is shallow clone, clone the object and not the object of property references, and when modifications are scores of clone, cloned object will also change, that is, properties of two objects is a reference point the same object.

But just change Student class overridden clone () method can achieve a deep clone.

1 @Override
2 protected Student clone() throws CloneNotSupportedException {
3 Student student = (Student) super.clone();
4 Achievement achievement = student.getAchievement().clone();
5 student.setAchievement(achievement);
6 return student;
7 }

operation result:

I.e., in the Student class clone () method of the object Achievement subcloned once, and assigned to the Student object.

It is worth mentioning that the above-mentioned shallow copy clone only basic data attributes, without cloning reference attributes of other objects, but does not belong to the basic properties of the String object, which is why it?

This is because String objects are immutable objects, each modification in fact create a new object, rather than modify the original object, so when modifying the String property is actually open up a new space to store String objects, and the references to the memory, and the String property of the cloned object or pointing to the original memory address, so the String object also performed with the same basic attributes in a shallow clone.

Guess you like

Origin www.cnblogs.com/zsh-blogs/p/11109744.html