浅拷贝
浅拷贝会创建一个新对象,如果这个对象的属性是基本类型,那么拷贝的就是基本数据类型的值。如果这个对象的属性是引用数据类型,那么拷贝的就是对象的引用地址。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| class Thcher implements Cloneable{ String name;
public Thcher() { }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override protected Thcher clone() throws CloneNotSupportedException { return (Thcher) super.clone(); } } class Student implements Cloneable { int age; Thcher thcher;
public Student() { }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public Thcher getThcher() { return thcher; }
public void setThcher(Thcher thcher) { this.thcher = thcher; }
@Override protected Student clone() throws CloneNotSupportedException {
return (Student) super.clone(); } }
public class CopyTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student();
student.age = 1; student.thcher = new Thcher(); student.thcher.name = "xiaowang";
Student stu2 = student.clone(); System.out.println(stu2 == student); System.out.println(stu2.thcher == student.thcher); } }
|

深拷贝
深拷贝会将对象的所有属性都浅拷贝一份。比如:对于引用变量来说,他会创建一个新的引用,拷贝的对象指向这个新的引用。
深拷贝相比于浅拷贝速度较慢并且花销较大
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| class Thcher implements Cloneable{ String name;
public Thcher() { }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@Override protected Thcher clone() throws CloneNotSupportedException { return (Thcher) super.clone(); } } class Student implements Cloneable { int age; Thcher thcher;
public Student() { }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public Thcher getThcher() { return thcher; }
public void setThcher(Thcher thcher) { this.thcher = thcher; }
@Override protected Student clone() throws CloneNotSupportedException {
Student student = new Student(); student.thcher = this.thcher.clone(); student.age = this.age; return student; } }
public class CopyTest {
public static void main(String[] args) throws CloneNotSupportedException {
Student student = new Student();
student.age = 1; student.thcher = new Thcher(); student.thcher.name = "xiaowang"; Student stu2 = student.clone(); System.out.println(stu2 == student); System.out.println(stu2.thcher == student.thcher); } }
|
