深拷贝基本介绍
- 复制对象的所有基本数据类型的成员变量值
- 为所有引用数据类型的成员变量申请存储空间,并复制每个引用数据类型成员变量所引用的对象,直到该对象可达的所有对象。也就是说,对象进行深拷贝要对整个对象进行拷贝
- 深拷贝实现方式1:重写clone方法来实现深拷贝
- 深拷贝实现方式2:通过对象序列化实现深拷贝
package com.young.prototype.deepclone;
import java.io.Serializable;
/**
* @author Shaw_Young
* @date 2020/10/6 15:09
*/
public class DeepCloneTarget implements Serializable, Cloneable {
private static final long serialVersionUid = 1L;
private String cloneName;
private String cloneClass;
public DeepCloneTarget(String cloneName, String cloneClass) {
this.cloneName = cloneName;
this.cloneClass = cloneClass;
}
public String getCloneName() {
return cloneName;
}
public void setCloneName(String cloneName) {
this.cloneName = cloneName;
}
public String getCloneClass() {
return cloneClass;
}
public void setCloneClass(String cloneClass) {
this.cloneClass = cloneClass;
}
/**
* 因为该类的属性,都是String,因此我们这里使用默认的clone完成即可
*/
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package com.young.prototype.deepclone;
import java.io.*;
/**
* @author Shaw_Young
* @date 2020/10/6 15:12
*/
public class DeepPrototype implements Serializable, Cloneable {
public String name;
public DeepCloneTarget deepCloneTarget;
public DeepPrototype() {
super();
}
/**
* 深拷贝: 方式1使用clone方法
*/
@Override
protected Object clone() throws CloneNotSupportedException {
Object deep = null;
//这里完成对基本数据类型(属性)和字符串的克隆
deep = super.clone();
//对引用类型的属性,进行单独处理
DeepPrototype deepPrototype = (DeepPrototype) deep;
deepPrototype.deepCloneTarget = (DeepCloneTarget) deepCloneTarget.clone();
return deep;
}
/**
* 深拷贝: 方式2通过对象的序列化实现深拷贝,推荐使用
*/
public Object deepClone() {
//创建流对象
ByteArrayOutputStream bos = null;
ObjectOutputStream oos = null;
ByteArrayInputStream bis = null;
ObjectInputStream ois = null;
try {
//序列化操作
bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(this);//当前这个对象以对象流的方式输出
//反序列化
bis = new ByteArrayInputStream(bos.toByteArray());
ois = new ObjectInputStream(bis);
DeepPrototype copyObj = (DeepPrototype) ois.readObject();
return copyObj;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (bos != null) {
bos.close();
}
if (oos != null) {
oos.close();
}
if (bis != null) {
bis.close();
}
if (ois != null) {
ois.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
package com.young.prototype.deepclone;
/**
* @author Shaw_Young
* @date 2020/10/6 15:21
*/
public class Client {
public static void main(String[] args) throws CloneNotSupportedException {
DeepPrototype p = new DeepPrototype();
p.name = "宋江";
p.deepCloneTarget = new DeepCloneTarget("大牛", "大牛的类");
// 方式1,完成深拷贝
// DeepPrototype p2 = (DeepPrototype) p.clone();
// System.out.println(p.deepCloneTarget.hashCode());
// System.out.println(p2.deepCloneTarget.hashCode());
// 方式2,完成深拷贝
DeepPrototype p2 = (DeepPrototype) p.deepClone();
System.out.println(p.deepCloneTarget.hashCode());
System.out.println(p2.deepCloneTarget.hashCode());
}
}
网友评论