浅拷贝
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept implements Cloneable{
private int id;
private String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Cloneable {
private int id;
private String name;
private Dept dept;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public static void main(String[] args) throws Exception{
Dept dept = new Dept(1, "事业部");
User user = new User(1, "张三", dept);
User userCopy01 = (User) user.clone();
System.out.println(user);
dept.setId(2);
System.out.println(userCopy01);
}
修改部门id,浅拷贝出来的对象里面的值会发生变化
深拷贝
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Dept implements Cloneable{
private int id;
private String name;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User implements Cloneable {
private int id;
private String name;
private Dept dept;
@Override
protected Object clone() throws CloneNotSupportedException {
User user = (User) super.clone();
Dept dept = (Dept) user.getDept().clone();
user.setDept(dept);
return user;
}
}
public static void main(String[] args) throws Exception{
Dept dept = new Dept(1, "事业部");
User user = new User(1, "张三", dept);
User userCopy01 = (User) user.clone();
System.out.println(user);
dept.setId(2);
System.out.println("--------" + userCopy01);
}
|