shadow clone and deep clone
要让一个对象进行克隆,其实就是两个步骤:
1. 让该类实现java.lang.Cloneable接口;
2. 重写(override)Object类的clone()方法。
⑴浅复制(浅克隆)
被复制对象的所有变量都含有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。换言之,浅复制仅仅复制所考虑的对象,而不
复制它所引用的对象。
⑵深复制(深克隆)
被复制对象的所有变量都含有与原来的对象相同的值,除去那些引用其他对象的变量。那些引用其他对象的变量将指向被复制过的新对象,而不再是原
有的那些被引用的对象。换言之,深复制把要复制的对象所引用的对象都复制了一遍。
Shadow Clone:
public class Professor implements Cloneable{
public int ID;
public String name;
}
public class Student implements Cloneable{
public int ID;
public Professor mProfessor;
public Student() {
mProfessor = new Professor();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
public static void main(String[] args) throws CloneNotSupportedException {
//deep clone: the reference of mProfessor is not changed
Student s1 = new Student();
s1.ID = 123;
s1.mProfessor.name = "abc";
Student s2 = (Student)s1.clone();
System.out.println(s2.ID); //123
System.out.println(s2.mProfessor.name); //abc
s1.ID = 456;
s1.mProfessor.name = "def";
System.out.println(s2.ID);//123
System.out.println(s2.mProfessor.name); //def
}
}
result:
123
abc
123
def
Deep Clone:
public class Professor implements Cloneable{ public int ID; public String name; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
public class Student implements Cloneable{ public int ID; public Professor mProfessor; public Student() { mProfessor = new Professor(); } @Override protected Object clone() throws CloneNotSupportedException { Student student = (Student)super.clone(); student.mProfessor = (Professor)student.mProfessor.clone(); return student; } public static void main(String[] args) throws CloneNotSupportedException { //deep clone: the reference of mProfessor is not changed Student s1 = new Student(); s1.ID = 123; s1.mProfessor.name = "abc"; Student s2 = (Student)s1.clone(); System.out.println(s2.ID); //123 System.out.println(s2.mProfessor.name); //abc s1.ID = 456; s1.mProfessor.name = "def"; System.out.println(s2.ID);//123 System.out.println(s2.mProfessor.name); //abc } }
result:
123
abc
123
abc

浙公网安备 33010602011771号