JAVA-Clone 对象拷贝

JAVA 中对象的赋值是复制对象的引用,即复制引用

public static void main(String[] args) {
User user = new User(1,"asds",18);
User user1 = user; System.out.println(user);
System.out.println(user1);
}

JAVA-Clone 对象拷贝

JAVA 中复制对象(克隆副本,互不影响)

使用 clone() 方法要求被克隆对象实现 Cloneable 接口,修改覆盖的 clone() 方法的修饰符为 public

public class User implements Cloneable {
private Integer id;
private String name;
private Integer age; @Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}

再测试

public static void main(String[] args) throws CloneNotSupportedException {
User user = new User(1,"asds",18);
User user1 = (User) user.clone(); System.out.println(user);
System.out.println(user1);
}

JAVA-Clone 对象拷贝

浅拷贝

public class Address {
private String address;
public class User implements Cloneable {
private Integer id;
private String name;
private Integer age;
private Address address; @Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}

测试

public static void main(String[] args) throws CloneNotSupportedException {
Address address = new Address("wuhan");
User user = new User(1,"asds",18,address);
User user1 = (User) user.clone(); // System.identityHashCode() 获取对象唯一标识,若对象不重写 hashCode() 则值和 Object.hashCode() 一样
System.out.println(System.identityHashCode(user)+"\t"+user);
System.out.println(System.identityHashCode(user1)+"\t"+user1); user.getAddress().setAddress("beijing"); System.out.println(user.hashCode()+"\t"+user);
System.out.println(user1.hashCode()+"\t"+user1);
}

JAVA-Clone 对象拷贝

只修改 user,但 user1 也被修改

clone() 方法:属性为基本类型拷贝其值,属性为非基本类型拷贝其引用

深拷贝

public class Address implements Cloneable {
private String address; @Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
public class User implements Cloneable {
private Integer id;
private String name;
private Integer age;
private Address address; @Override
public Object clone() throws CloneNotSupportedException {
Object clone = super.clone();
Object addressClone = ((User) clone).getAddress().clone();
((User) clone).setAddress((Address) addressClone);
return clone;
}

再测试

JAVA-Clone 对象拷贝

实现完整的深拷贝,需要被复制对象的继承链、引用链上的每一个对象都实现克隆机制

被克隆的对象的属性都是基本类型,那只需要被克隆类实现 cloneable 接口即可,若对象的属性包含其他非基本类型对象,那么这些非基本类型的对象都需要实现 cloneable 接口

对象属性少这样做还可以完成深拷贝,如果有多个对象属性,多层引用关系,就会比较棘手,这时候可用JAVA的序列化机制来完成对象的深拷贝


https://blog.****.net/54powerman/article/details/64920431

上一篇:【5.1送礼】国内第一部Matlab和C#.Net混合编程视频教程【免费】


下一篇:Spring源码系列(二)--bean组件的源码分析