您的位置:首页 > 其它

冷藏 解冻 深拷贝deepclone

2009-12-01 19:14 399 查看
出处:http://blog.csdn.net/dl88250/archive/2007/08/26/1759978.aspx

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());
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: