淺拷貝和深拷貝的定義:
淺拷貝:
被復制對象的所有變量都含有與原來的對象相同的值,而所有的對其他對象的引用仍然指向原來的對象。即對象的淺拷貝會對“主”對象進行拷貝,但不會復制主對象里面的對象。”里面的對象“會在原來的對象和它的副本之間共享。簡而言之,淺拷貝僅僅復制所考慮的對象,而不復制它所引用的對象。
深拷貝:
深拷貝是一個整個獨立的對象拷貝,深拷貝會拷貝所有的屬性,並拷貝屬性指向的動態分配的內存。當對象和它所引用的對象一起拷貝時即發生深拷貝。深拷貝相比於淺拷貝速度較慢並且花銷較大。簡而言之,深拷貝把要復制的對象所引用的對象都復制了一遍。
Teacher teacher = new Teacher();
teacher.name = "原老師";
teacher.age = 28;
Student student1 = new Student();
student1.name = "原學生";
student1.age = 18;
student1.teacher = teacher;
Student student2 = (Student) student1.clone();
System.out.println("-------------拷貝后-------------");
System.out.println(student2.name);
System.out.println(student2.age);
System.out.println(student2.teacher.name);
System.out.println(student2.teacher.age);
System.out.println("-------------修改老師的信息后-------------");
// 修改老師的信息
teacher.name = "新老師";
System.out.println("student1的teacher為: " + student1.teacher.name);
System.out.println("student2的teacher為: " + student2.teacher.name);
class Teacher implements Cloneable {
public String name;
public int age;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Student implements Cloneable {
public String name;
public int age;
public Teacher teacher;
public Object clone() throws CloneNotSupportedException {
// 淺復制時:
// return super.clone();
// 深復制時:
Student student = (Student) super.clone();
// 本來是淺復制,現在將Teacher對象復制一份並重新賦值進來
student.teacher = (Teacher) this.teacher.clone();
return student;
}
}
淺拷貝>輸出結果:
-------------拷貝后-------------
原學生
18
原老師
28
-------------修改老師的信息后-------------
student1的teacher為: 原老師
student2的teacher為: 原老師
結果分析:
兩個引用student1和student2指向不同的兩個對象,但是兩個引用student1和student2中的兩個teacher引用指向的是同一個對象,所以說明是"淺拷貝"。
深拷貝>輸出結果:
-------------拷貝后-------------
原學生
18
原老師
28
-------------修改老師的信息后-------------
student1的teacher為: 新老師
student2的teacher為: 原老師
結果分析:
兩個引用student1和student2指向不同的兩個對象,兩個引用student1和student2中的兩個teacher引用指向的是兩個對象,但對teacher對象的修改只能影響student1對象,所以說明是"深拷貝"。