浅拷贝概念
深拷贝概念
@Data
@Slf4j
public class Sheep implements Cloneable {
private String name;
private int age;
private String color;
private Sheep friend;
public Sheep(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
@Override
protected Object clone(){
Sheep sheep = null;
try {
sheep = (Sheep) super.clone();
} catch (Exception e) {
log.info("" + e);
}
return sheep;
}
}
@Data
public class DeepPrptoType implements Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private String name;
private DeepCloneableTarget deepCloneableTarget;
public DeepPrptoType() {
}
//深拷贝方式1 使用clone方法
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
//这里对基本数据类型和String对克隆
deep = super.clone();
DeepPrptoType deepPrptoType = (DeepPrptoType) deep;
deepPrptoType.deepCloneableTarget = (DeepCloneableTarget) deepCloneableTarget.clone();
return deepPrptoType;
}
//深拷贝,方式2 通过对象的序列化实现(推荐使用)
public static <T extends Serializable> T deepClone(T obj) {
T cloneObj = null;
try {
//写入字节流
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream obs = new ObjectOutputStream(out);
obs.writeObject(obj);
obs.close();
//分配内存,写入原始对象,生成新对象
ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream ois = new ObjectInputStream(ios);
//返回生成的新对象
cloneObj = (T) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
return cloneObj;
}
}
public class Client2 {
public static void main(String[] args) throws CloneNotSupportedException {
DeepPrptoType p = new DeepPrptoType();
p.setName("深拷贝");
p.setDeepCloneableTarget(new DeepCloneableTarget("大牛", "哈哈"));
//方式一:深拷贝
DeepPrptoType p2 = (DeepPrptoType) p.clone();
System.out.println(p.getName() + p.getDeepCloneableTarget().hashCode());
System.out.println(p2.getName() + p2.getDeepCloneableTarget().hashCode());
//通过序列化和反序列化实现深拷贝,说明引用类型所指向的对象也被clone了
DeepPrptoType p3 = DeepPrptoType.deepClone(p);
System.out.println(p3.getName() + p3.getDeepCloneableTarget().hashCode());
}
}
文章版权声明
1 原创文章作者:竹叶秋林,如若转载,请注明出处: https://www.52hwl.com/38398.html
2 温馨提示:软件侵权请联系469472785#qq.com(三天内删除相关链接)资源失效请留言反馈
3 下载提示:如遇蓝奏云无法访问,请修改lanzous(把s修改成x)
4 免责声明:本站为个人博客,所有软件信息均来自网络 修改版软件,加群广告提示为修改者自留,非本站信息,注意鉴别