对于数组的拷贝,如果是简单类型的话是深拷贝,如果是引用类型的话是浅拷贝,但是因为java是面向对象的,在回答面试官问题的时候,我们可以不用说的这么细,可以直接说浅拷贝。
代码示例1
class Person implements Cloneable{
public int age;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class TestDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person();
Person person2 = (Person) person1.clone();
System.out.println(person1.age);
System.out.println(person2.age);
System.out.println("=======修改=======");
person2.age = 99;
System.out.println(person1.age);
System.out.println(person2.age);
}
}
输出为: 因为改变的是简单类型,所以这种情况是深拷贝。
代码示例2
class Money{
double money = 12.5;
}
class Person implements Cloneable{
public int age;
Money m = new Money();
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class TestDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person();
Person person2 = (Person) person1.clone();
System.out.println(person1.m.money);
System.out.println(person2.m.money);
System.out.println("=========修改==========");
person2.m.money = 99.9;
System.out.println(person1.m.money);
System.out.println(person2.m.money);
}
}
输出为: 可以参考以下图分析: 这种情况就是浅拷贝,那么可以将这个浅拷贝变成深拷贝吗?只需要将Money也克隆一下
class Money implements Cloneable{
double money = 12.5;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
class Person implements Cloneable{
public int age;
Money m = new Money();
@Override
protected Object clone() throws CloneNotSupportedException {
Person p = (Person)super.clone();
p.m = (Money) this.m.clone();
return p;
}
}
public class TestDemo {
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person();
Person person2 = (Person) person1.clone();
System.out.println(person1.m.money);
System.out.println(person2.m.money);
System.out.println("=========修改==========");
person2.m.money = 99.9;
System.out.println(person1.m.money);
System.out.println(person2.m.money);
}
}
输出为: 这样就就将浅拷贝转变成了深拷贝,可以参考以下图分析:
|