Object
类中存在一个
clone
方法
,
调用这个方法可以创建一个对象的
"
拷贝
".
但是要想合法调用
clone
方法
,
必须要先实现 Clonable
接口
,
否则就会抛出
CloneNotSupportedException
异常
public class Person implements Cloneable{
public int age;
public Person(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Person person1=new Person(18);
Person person2= (Person) person1.clone();
System.out.println(person2==person1);
}
}
输出是false,为什么呢?
此时比较的是person1和person2的地址,所以输出false
浅拷贝
public class Money implements Cloneable{
public int price=10;
@Override
public String toString() {
return "Money{" +
"price=" + price +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Person implements Cloneable{
public int age;
Money m=new Money();
public Person(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Person person1=new Person(18);
Person person2= (Person) person1.clone();
System.out.println(person1.m.price);
System.out.println(person2.m.price);
person1.m.price=88;
System.out.println(person1.m.price);
System.out.println(person2.m.price);
}
}
10
10
88
88
浅拷贝就是改变其中一个,另外一个也跟着改变。从内存上分析
深拷贝
public class Money implements Cloneable{
public int price=10;
@Override
public String toString() {
return "Money{" +
"price=" + price +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Person implements Cloneable{
public int age;
Money m=new Money();
public Person(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"age=" + age +
'}';
}
@Override
protected Object clone() throws CloneNotSupportedException {
Person temp= (Person) super.clone();
temp.m= (Money) this.m.clone();
return temp;
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Person person1=new Person(18);
Person person2= (Person) person1.clone();
System.out.println(person1.m.price);
System.out.println(person2.m.price);
person1.m.price=88;
System.out.println(person1.m.price);
System.out.println(person2.m.price);
}
}
10
10
88
10
内存分析