Java shallow and deep clone clone realization

First, why clone
       clone objects may contain some of the properties have been modified, retains the values you want to clone an object, but the object out of the new property is a whole new object, there is no corresponding attribute value, we have to re each assign this object. So when you need a new object to hold the current object "state" only through cloned. Some people may ask, I took a temporary assignment of a property of this object to the new object does not my new thing is also OK? Were able to achieve, but it is too cumbersome, In addition, the source code can be found clone is a native method soon, no doubt on the underlying implementation, speed.
Second, how to achieve cloning
        have the following main steps:
               a class object implement the Cloneable interface;
               2, covering clone () method of class Object (covering clone () method to access modifiers public, default is protected);
               . 3, in calling super.clone clone () method ().
Third, two different methods of cloning, shallow clone (shallowClone) and a deep clone (DeepClone).
        Shallow clone is a copy of the object only when the copy of the object itself (including the basic variable object), without copying the object contains references to the objects.
        Deep clone only copy of the object itself, and copy all objects contained references to the objects.
        For example, more clearly:

  Shallow clone

       package org.com.huang.test;
  public class Student implements Cloneable {
      private int age;
      private String name;
      public Student(int age, String name) {
          this.age = age;
          this.name = name;
      }
      public int getAge() {
          return age;
      }
      public void setAge(int age) {
          this.age = age;
      }
      public String getName() {
          return name;
      }
      public void setName(String name) {
          this.name = name;
      }
      @Override
      public String toString() {
          return "Student [age=" + age + ", name=" + name + "]";
      }
      @Override
      public Object clone() throws CloneNotSupportedException {
          // TODO Auto-generated method stub
          return super.clone();
      }
      public static void main(String[] args) throws CloneNotSupportedException {
          Student student1 = new Student(20, "张三");
          Student student2 = (Student) student1.clone();
          student2.setAge(22);// 注意修改student2的age值 但是没有影响 student1的值
          System.out.println("student1:" + student1.getName() + "-->"+ student1.getAge());
          System.out.println("student2:" + student2.getName() + "-->"+ student2.getAge());
 
      }
   }

  运行结果:
  student1:张三-->20
  student2:张三-->22
  问题:引入克隆导致的问题
      package org.com.huang.test;
 
      class Teacher implements Cloneable {
          private String name;
          private Student student;
          public String getName() {
            return name;
         }
        public void setName(String name) {
            t  his.name = name;
           }
          public Student getStudent() {
              return student;
           }
           public void setStudent(Student student) {
             this.student = student;
           }
           @Override
           public String toString() {
             return "Teacher [name=" + name + ", student=" + student + "]";
           }
           @Override
           public Object clone() throws CloneNotSupportedException {
            // TODO Auto-generated method stub
            return super.clone();
            }
         public static void main(String[] args) throws CloneNotSupportedException {
                Student s1 = new Student();
                 s1.setAge(20);
                 s1.setName("张三");
                Teacher teacher1 = new Teacher();
                teacher1.setName("小赵老师");
                teacher1.setStudent(s1);
               //为什么会出现以下结果, Teacher中的clone方法
               Teacher teacher2 = (Teacher)teacher1.clone();
               Student s2 = teacher2.getStudent();
                s2.setName("李四");
                s2.setAge(30);
                System.out.println("teacher1:"+teacher1);
                System.out.println("teacher2:"+teacher2);
          }
          }
      运行结果:
     teacher1:Teacher [name=小赵老师, student=Student [age=30, name=李四]]
     teacher2:Teacher [name=小赵老师, student=Student [age=30, name=李四]
   深克隆
         要克隆的类和类中所有非基本数据类型的属性对应的类(注意clone()方法)
           package org.com.huang.test;
           class Teacher implements Cloneable {
               private String name;
               private Student student;
           public String getName() {
               return name;
           }
           public void setName(String name) {
              this.name = name;
           }
          public Student getStudent() {
             return student;
          }
         public void setStudent(Student student) {
             this.student = student;
         }
         @Override
        public String toString() {
             return "Teacher [name=" + name + ", student=" + student + "]";
         }
         @Override
        public Object clone() throws CloneNotSupportedException {
              // TODO Auto-generated method stub
              //注意以下代码
              Teacher teacher = (Teacher)super.clone();
               teacher.setStudent((Student)teacher.getStudent().clone());
               return teacher;
         }
         public static void main(String[] args) throws CloneNotSupportedException {
               Student s1 = new Student();
               s1.setAge(20);
              s1.setName("张三");
              Teacher teacher1 = new Teacher();
               teacher1.setName("小赵老师");
               teacher1.setStudent(s1);
              Teacher teacher2 = (Teacher)teacher1.clone();
               teacher2.setName("小明老师");
               Student s2 = teacher2.getStudent();
               s2.setName("李四");
               s2.setAge(30);
               System.out.println("teacher1:"+teacher1);
              System.out.println("teacher2:"+teacher2);
          }
    
         }
    运行结果:
    teacher1:Teacher [name=小赵老师, student=Student [age=20, name=张三]]
    teacher2:Teacher [name=小明老师, student=Student [age=30, name=李四]]

Guess you like

Origin www.cnblogs.com/rainyfrog/p/10961745.html