#浅克隆是克隆任何对象引用与基础数据类型的值
public class Test1 {
public static void main(String []args) throws CloneNotSupportedException {
Person person1 = new Person("qfe",1000);
Person person2 = person1.clone();
System.out.println(person1==person2);
person1.name = "yang";
person1.list.add(100);
person1.age = 1000;
System.out.println(person1.name);
System.out.println(person1.list);
System.out.println(person2.name);
System.out.println(person2.list);
System.out.println(person1.list==person2.list);
System.out.println(person1.age== person2.age);
}
}
class Person implements Cloneable{
public String name;
int age;
LinkedList<Integer> list;
public Person(String name,int age){
this.name = name;
this.age = age;
list = new LinkedList<>();
list.add(110000);
}
@Override
public Person clone() throws CloneNotSupportedException {
Person person = (Person)super.clone();
return person;
}
}
我们发现person1中的list增加100,person2中的list也相应改变了。person1.list==person2.list为true
#深克隆克隆的对象与原对象互不影响。集合容器中的clone方法是深克隆。
public class Test1 {
public static void main(String []args) throws CloneNotSupportedException {
Person person1 = new Person("qfe",1000);
Person person2 = person1.clone();
System.out.println(person1==person2);
person1.name = "yang";
person1.list.add(100);
person1.age = 1000;
System.out.println(person1.name);
System.out.println(person1.list);
System.out.println(person2.name);
System.out.println(person2.list);
System.out.println(person1.list==person2.list);
System.out.println(person1.animal==person2.animal);
System.out.println(person1.age== person2.age);
System.out.println(person1.age.intValue()== person2.age.intValue());
System.out.println(person1.age.equals(person2.age));
}
}
class Person implements Cloneable{
public String name;
Integer age;
LinkedList<Integer> list;
Animal animal = new Animal();
public Person(String name,int age){
this.name = name;
this.age = age;
list = new LinkedList<>();
list.add(110000);
}
public Person(){}
@Override
public Person clone() throws CloneNotSupportedException {
Person person = (Person)super.clone();
person.list = (LinkedList<Integer>) list.clone();
return person;
}
}
class Animal{
}
上述代码,我们需要注意两点,一是:在Person类中的clone方法里面,person.list用了list的深克隆。所以person1.list==person2.list的结果为false,二是:我们把int age 改为了Interge age person1.age =1000 结果导致了person1.age ==person2.age 为false,这是因为int 的包装类在-128 - 127之间只存在一个对象,范围外的重新赋值拿到的是另一个对象。