冷藏 解冻 深拷贝deepclone
2009-12-01 19:14
399 查看
出处:http://blog.csdn.net/dl88250/archive/2007/08/26/1759978.aspx
前拷贝需要实现Cloneable接口,深拷贝需要实现Serializable接口。
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 然后将对象从流里读出来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
public class Square implements Cloneable, Serializable { private Point location = new Point(0, 0); private float sideLength = 1F; @Override public Object clone() { Square tmp = null; try { tmp = (Square) super.clone(); } catch (CloneNotSupportedException cnse) { cnse.printStackTrace(); } finally { return tmp; } } /** * 深克隆方法 * @return */ public Object deepClone() throws IOException, OptionalDataException, ClassNotFoundException { // 首先将对象写到流里 ByteArrayOutputStream bo = new ByteArrayOutputStream(); ObjectOutputStream oo = new ObjectOutputStream(bo); oo.writeObject(this); // 然后将对象从流里读出来 ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray()); ObjectInputStream oi = new ObjectInputStream(bi); return (oi.readObject()); } /** * @return the location */ public Point getLocation() { return location; } /** * @param location the location to set */ public void setLocation(Point location) { this.location = location; } /** * @return the sideLength */ public float getSideLength() { return sideLength; } /** * @param sideLength the sideLength to set */ public void setSideLength(float sideLength) { this.sideLength = sideLength; } }
前拷贝需要实现Cloneable接口,深拷贝需要实现Serializable接口。
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(this);
// 然后将对象从流里读出来
ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
ObjectInputStream oi = new ObjectInputStream(bi);
return (oi.readObject());
相关文章推荐
- java浅拷贝(shallow clone)与深拷贝(deep clone)
- 深拷贝(deep clone)和浅拷贝(shallow copy)
- Java中深拷贝(Deep Clone)与浅拷贝(Shallow Clone)
- 深拷贝(Deep Clone)与浅拷贝(Shadow Clone)
- 深拷贝(deep clone)与浅拷贝(shallow clone)
- 深拷贝与浅拷贝(Deep Copy and Shallow Copy)
- 【iPhone开发】深拷贝和浅拷贝 Deep copy and Shadow copy
- javascript深拷贝(deepClone)详解
- 一眼看懂深浅拷贝(clone)-C#
- java 重写接口Cloneable的Clone方法 拷贝对象
- 浅拷贝和深拷贝(谈谈java中的clone)
- Ruby中如何复制对象 (deep clone)(转载)
- 【python】copy浅拷贝和deepcopy深拷贝
- Implementing Deep Cloning via Serializing objects使用Serializable来实现深拷贝
- Shallow Copy(影子拷贝) VS Deep Copy(深拷贝)
- JavaScript深度复制(deep clone)的实现方法
- [置顶] C++/C#中堆栈、对象内存模型、深浅拷贝、Array.Clone方法
- Javascript对象拷贝(clone)
- Java中shallow clone 与deep Clone的区别