赞
踩
浅拷贝见博客原型模式 浅拷贝
发送邮件,邮件中有附件,深拷贝实现了附件也拷贝了一份。在附件中再加入了一个对象,序列化后也复制了,实验证明深拷贝会将引用对象的引用对象也都复制
public class Test {
public static void main(String[] args) {
Email email = new Email(new Attachment());
Email copyEmail =(Email) email.deepClone();
System.out.println(email == copyEmail);
System.out.println(email.equals(copyEmail));
System.out.println(email.getAttachment() == copyEmail.getAttachment());
System.out.println(email.getAttachment().equals(copyEmail.getAttachment()));
System.out.println(email.getAttachment().getCat() == copyEmail.getAttachment().getCat());
}
}
class Attachment implements Serializable{
private Cat cat = new Cat();
public void download(){
System.out.println("下载附件");
}
public Cat getCat() {
return cat;
}
}
class Email implements Serializable{
private Attachment attachment;
public Email(Attachment attachment) {
this.attachment = attachment;
}
public Object deepClone(){
try {
//将对象写入流中
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
oos.close();
//将对象从流中取出
InputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
Object o = ois.readObject();
ois.close();
return o;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
public Attachment getAttachment() {
return attachment;
}
public void display(){
System.out.println("查看邮件");
}
}
//Email类没有重写equals方法,所以这里equals和==是一样的,如果是String重写了equals方法的话会返回true的。
输出:false
false
false
false
false
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。