Java深克隆和浅克隆
实现克隆
- 对象的类实现Cloneable接口;
- 覆盖Object类的clone()方法 ;
- 在clone()方法中调用super.clone();
浅克隆和深克隆
浅克隆是指拷贝对象时仅仅拷贝对象本身(包括对象中的基本变量),而不拷贝对象包含的引用指向的对象。
深克隆不仅拷贝对象本身,而且拷贝对象包含的引用指向的所有对象。
@Data
class Father implements Cloneable{
private String name;
private Integer age;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
@Test
void testClone() throws CloneNotSupportedException {
Father father = new Father();
father.setName("zs");
father.setAge(18);
Father clone = (Father) father.clone();
father.setName("ls");
System.out.println(father);//Father(name=ls, age=18)
System.out.println(clone);//Father(name=zs, age=18)
}
//注意修改father的name值 但是没有影响 clone的值
@Data
class Father implements Cloneable{
private String name;
Child child;
@Override
public Object clone() throws CloneNotSupportedException {
Father father = (Father)super.clone();
father.setChild((Child)father.getChild().clone());
return father;
}
}
@Data
class Child implements Cloneable{
private String name;
private Integer age;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
@Test
void testClone() throws CloneNotSupportedException {
Father father = new Father();
father.setName("zs");
Child child = new Child();
child.setName("儿子");
child.setAge(15);
father.setChild(child);
Father clone = (Father) father.clone();
Child child1 = father.getChild();
child1.setName("儿子2");
father.setChild(child1);
System.out.println();
System.out.println(father);//Child(name=儿子2, age=15))
System.out.println(clone);//Child(name=儿子, age=15))
//此时修改原来对象的值,是不会影响复制的对象的
}