首页 > 代码库 > Java clone()

Java clone()

1.java里的clone分为:
A:浅复制(浅克隆): 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
b:深复制(深克隆):深复制把要复制的对象所引用的对象都复制了一遍。
Java中对象的克隆,为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。必须要遵循下面三点
1.在派生类中覆盖基类的clone()方法,并声明为public【Object类中的clone()方法为protected的】。
2.在派生类的clone()方法中,调用super.clone()。
3.在派生类中实现Cloneable接口。

Object类里的clone方法是浅复制(浅克隆)

浅复制(浅克隆)的例子如下:

 

//浅复制(浅克隆): 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。  //深复制(深克隆):深复制把要复制的对象所引用的对象都复制了一遍。  //  //Java中对象的克隆,为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。必须要遵循下面三点  //1.在派生类中覆盖基类的clone()方法,并声明为public【Object类中的clone()方法为protected的】。  //2.在派生类的clone()方法中,调用super.clone()。  //3.在派生类中实现Cloneable接口。    public class Clone {    public static void main(String[] args) throws Exception {        // teacher对象将被clone出来的Student对象共享.        Teacher teacher = new Teacher();        teacher.setAge(40);        teacher.setName("Teacher zhang");        Student student1 = new Student();        student1.setAge(20);        student1.setName("zhangsan");        student1.setTeacher(teacher);        // 复制出来一个对象student2        Student student2 = (Student) student1.clone();        System.out.println(student2.getAge());        System.out.println(student2.getName());        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");        System.out.println(student1.getTeacher().getAge());        System.out.println(student1.getTeacher().getName());        // 修改student2的引用对象        student2.getTeacher().setAge(50);        student2.getTeacher().setName("Teacher Li");        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");        System.out.println(student1.getTeacher().getAge());        System.out.println(student1.getTeacher().getName());    }}class Teacher {    public int age;    public String 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;    }}class Student implements Cloneable {    public int age;    public String name;    public Teacher teacher;    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;    }    public Teacher getTeacher() {        return teacher;    }    public void setTeacher(Teacher teacher) {        this.teacher = teacher;    }    @Override    public Object clone() throws CloneNotSupportedException {        return super.clone();    }}
  1. 输出结果为:  
  2. 20  
  3. zhangsan  
  4. ~~~~~~~~~~~~~~~~~~~~~~  
  5. 40  
  6. Teacher zhang  
  7. ~~~~~~~~~~~~~~~~~~~~~~  
  8. 50  
  9. Teacher Li  
 

 

2.深复制(深Clone)例子:

 1 public class DeepClone { 2  3  4         public static void main(String[] args) throws Exception { 5             // teacher对象将不被clone出来的Student对象共享. 6             Teacher teacher = new Teacher(); 7             teacher.setAge(40); 8             teacher.setName("Teacher zhang"); 9 10             Student student1 = new Student();11             student1.setAge(20);12             student1.setName("zhangsan");13             student1.setTeacher(teacher);14 15             // 复制出来一个对象student216             Student student2 = (Student) student1.clone();17             System.out.println(student2.getAge());18             System.out.println(student2.getName());19 20             System.out.println("~~~~~~~~~~~~~~~~~~~~~~");21             System.out.println(student1.getTeacher().getAge());22             System.out.println(student1.getTeacher().getName());23 24             // 修改student2的引用对象25             student2.getTeacher().setAge(50);26             student2.getTeacher().setName("Teacher Li");27 28             System.out.println("~~~~~~~~~~~~~~~~~~~~~~");29             System.out.println(student1.getTeacher().getAge());30             System.out.println(student1.getTeacher().getName());31         }32     }33 34     class Teacher implements Cloneable {35         public int age;36         public String name;37 38         public int getAge() {39             return age;40         }41 42         public void setAge(int age) {43             this.age = age;44         }45 46         public String getName() {47             return name;48         }49 50         public void setName(String name) {51             this.name = name;52         }53 54         @Override55         public Object clone() throws CloneNotSupportedException {56             return super.clone();57         }58 59     }60 61     class Student implements Cloneable {62 63         public int age;64         public String name;65         public Teacher teacher;66 67         public int getAge() {68             return age;69         }70 71         public void setAge(int age) {72             this.age = age;73         }74 75         public String getName() {76             return name;77         }78 79         public void setName(String name) {80             this.name = name;81         }82 83         public Teacher getTeacher() {84             return teacher;85         }86 87         public void setTeacher(Teacher teacher) {88             this.teacher = teacher;89         }90 91         @Override92         public Object clone() throws CloneNotSupportedException {93             Student student = (Student) super.clone();94             // 将引用的对象teacher也clone下95             student.setTeacher((Teacher)(student.getTeacher().clone()));96             return student;97         }98 99     }
  1. 输出结果为:  
  2. 20  
  3. zhangsan  
  4. ~~~~~~~~~~~~~~~~~~~~~~  
  5. 40  
  6. Teacher zhang  
  7. ~~~~~~~~~~~~~~~~~~~~~~  
  8. 40  
  9. Teacher zhang 

3.利用序列化来做深复制,把对象写到流里的过程是序列化(Serilization)过程,而把对象从流中读出来的过程则叫做反序列化(Deserialization)过程。应当指出的是,写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。,利用这个特性,可以做深拷贝

 

import java.io.ByteArrayInputStream;  import java.io.ByteArrayOutputStream;  import java.io.ObjectInputStream;  import java.io.ObjectOutputStream;  import java.io.Serializable;  //利用序列化来做深复制  //深clone  public class DeepCloneTest {        public static void main(String[] args) throws Exception{          //teacher对象将不被clone出来的Student对象共享.          Teacher teacher = new Teacher();          teacher.setAge(40);          teacher.setName("Teacher zhang");                    Student student1 = new Student();          student1.setAge(20);          student1.setName("zhangsan");          student1.setTeacher(teacher);                    //复制出来一个对象student2          Student student2 = (Student)student1.deepCopy();        System.out.println(student2.getAge());          System.out.println(student2.getName());                              System.out.println("~~~~~~~~~~~~~~~~~~~~~~");          System.out.println(student1.getTeacher().getAge());          System.out.println(student1.getTeacher().getName());                              //修改student2的引用对象          student2.getTeacher().setAge(50);          student2.getTeacher().setName("Teacher Li");                    System.out.println("~~~~~~~~~~~~~~~~~~~~~~");          System.out.println(student1.getTeacher().getAge());          System.out.println(student1.getTeacher().getName());      }  }    class Teacher implements Serializable{            private static final long serialVersionUID = -8834559347461591191L;            public int age;      public String 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;      }        }    class Student implements Serializable{            //serialVersionUID 如果你的对象序列化后存到硬盘上面后,可是后来你却更改了类的field(增加或减少或改名),当你反序列化时,就会出现Exception的,这样就会造成不兼容性的问题。       //但当serialVersionUID相同时,它就会将不一样的field以type的缺省值赋值(如int型的是0,String型的是null等),这个可以避开不兼容性的问题。所以最好给serialVersionUID赋值      private static final long serialVersionUID = 7991552226614088458L;            public int age ;      public String name;      public Teacher teacher;      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;      }      public Teacher getTeacher() {          return teacher;      }      public void setTeacher(Teacher teacher) {          this.teacher = teacher;      }            public Object deepCopy() throws Exception{          //将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝          ByteArrayOutputStream bos = new ByteArrayOutputStream();            ObjectOutputStream oos = new ObjectOutputStream(bos);            oos.writeObject(this);            //将流序列化成对象          ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());            ObjectInputStream ois = new ObjectInputStream(bis);            return ois.readObject();      }  
  1. 输出结果为:  
  2. 20  
  3. zhangsan  
  4. ~~~~~~~~~~~~~~~~~~~~~~  
  5. 40  
  6. Teacher zhang  
  7. ~~~~~~~~~~~~~~~~~~~~~~  
  8. 40  
  9. Teacher zhang