当拷贝一个变量时,原始变量与拷贝变量引用同一个对象,改变一个变量将对另一个对象产生影响。
Employee original = new Employee("Morty", 400000);
Employee copy = original;
copy.raiseSalary(10);//oops--also changed original
而clone()希望达到的目的是,在改变一个变量时对另一个变量没有影响。比如:
Employee original = new Employee("Morty", 400000);
Employee clone = (Employee) original.clone();
clone.raiseSalary(10);//original Not Changed
在一般情况下,调用Cloneable接口总没有错,比如下例在基本数据类型上clone()的应用,int、String这样的变量在克隆之后可以随意更改。但是注意,代码20行是Cloneable接口默认方法,在没有重写时默认为return (Object) super.clone();
,这样的clone称之为浅克隆。
public class CloneTest1 {
public static void main(String[] args) {
try {
Student morty = new Student(22, "Morty");
Student daisy = morty.clone();
daisy.setName("Daisy");
daisy.setAge(21);
System.out.println(morty);//Student{age=22, name='Morty'}
System.out.println(daisy);//Student{age=21, name='Daisy'}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
public static class Student implements Cloneable {
private int age;
private String name;
public Student clone() throws CloneNotSupportedException {
return (Student) super.clone();
}
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() {
final StringBuffer sb = new StringBuffer("Student{");
sb.append("age=").append(age);
sb.append(", name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
}
然而,一般的对象除了基本数据类型,都包含有自身独有的类,比如Teacher有自己的name,也有自己的Student。那么,克隆Teacher之后,新Teacher的Student类变量改变时,原来Teacher的Student类变量也像name变量一样不会变吗?在下面的代码中,teacher2首先克隆了teacher1的name和Student,之后更改了name,显然不会改变teacher1的name。更改Student类变量的name和age后,teacher1的Student类的name和age也改变了!说明clone操作很懒,它并没有为teacher2新建一个Student类变量,而是让它指向与teacher1同一个目标,或者说引用。
public class CloneTest2 {
public static void main(String[] args) {
try {
CloneTest1.Student student1 = new CloneTest1.Student(22, "morty");
Teacher teacher1 = new Teacher();
teacher1.setName("Dr.Rick");
teacher1.setAge(45);
teacher1.setStudent(student1);
Teacher teacher2 = (Teacher) teacher1.clone();
CloneTest1.Student student2 = teacher2.getStudent();
teacher2.setName("Dr.Ham");
teacher2.setAge(46);
student2.setAge(23);
student2.setName("daisy");
System.out.println(teacher1);//Teacher{name='Dr.Rick', age=45, student=Student{age=23, name='daisy'}}
System.out.println(teacher2);//Teacher{name='Dr.Ham', age=46, student=Student{age=23, name='daisy'}}
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
static class Teacher implements Cloneable {
private String name;
private int age;
private CloneTest1.Student student;
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 CloneTest1.Student getStudent() {
return student;
}
public void setStudent(CloneTest1.Student student) {
this.student = student;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Teacher{");
sb.append("name='").append(name).append('\'');
sb.append(", age=").append(age);
sb.append(", student=").append(student);
sb.append('}');
return sb.toString();
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();//依旧是浅克隆
}
}
}
问题出在return (Object) super.clone();
这行代码上,浅克隆并不会克隆除了基础数据类型之外的类。要想实现其他复杂类的克隆,避免编译器将复杂类简单地通过引用来处理,而非创立一个新的类,就需要重写clone()类。代码如下,注意第29~31行的写法。这样重写以后,改变teacher2的Student类就不会对teacher1产生影响。这样重写clone()类的clone称为深克隆。
public class CloneTest3 {
public static void main(String[] args) {
try {
CloneTest1.Student student1 = new CloneTest1.Student(22,"morty");
Teacher teacher1 = new Teacher();
teacher1.setStudent(student1);
teacher1.setName("Dr.Rick");
Teacher teacher2 = (Teacher) teacher1.clone();
teacher2.setName("Dr.Ham");
CloneTest1.Student student2 = (CloneTest1.Student) teacher2.getStudent();
student2.setName("daisy");
student2.setAge(22);
System.out.println(teacher1);//Teacher{name='Dr.Rick', student=Student{age=22, name='morty'}}
System.out.println(teacher2);//Teacher{name='Dr.Ham', student=Student{age=22, name='daisy'}}
} catch (Exception e) {
e.printStackTrace();
}
}
static class Teacher implements Cloneable {
private String name;
private CloneTest1.Student student;
@Override
protected Object clone() throws CloneNotSupportedException {
Teacher teacher = (Teacher) super.clone();
teacher.setStudent((CloneTest1.Student) teacher.getStudent().clone());
return teacher;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public CloneTest1.Student getStudent() {
return student;
}
public void setStudent(CloneTest1.Student student) {
this.student = student;
}
@Override
public String toString() {
final StringBuffer sb = new StringBuffer("Teacher{");
sb.append("name='").append(name).append('\'');
sb.append(", student=").append(student);
sb.append('}');
return sb.toString();
}
}
}
总结
浅克隆只克隆基本数据类型的变量,对于非基本类型数据仅仅让clone对象引用原来的数据,改变非基本数据类型,原来的数据也会改变。
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();//浅克隆
}
深克隆可以克隆所有数据类型的变量,只要在clone()方法里对特别的类进行重写。
@Override
protected Object clone() throws CloneNotSupportedException {
Teacher teacher = (Teacher) super.clone();
teacher.setStudent((CloneTest1.Student) teacher.getStudent().clone());
return teacher;//深克隆
}
把本文代码自己敲一遍就懂了浅拷贝和深拷贝。在实际应用中,由于这种clone操作太复杂,不适合大量引用的场景,一般都采用json格式记录各种数据。