浅拷贝概念
深拷贝概念
@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;}@Overrideprotected 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方法@Overrideprotected 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());}
}