首页 > 其他 > 详细

java 拷贝功能

时间:2014-01-25 18:50:27      阅读:332      评论:0      收藏:0      [点我收藏+]

java 中的 拷贝分为浅拷贝 和 深拷贝

浅拷贝需要实现Cloneable接口,深拷贝需要实现Serializable接口。

bubuko.com,布布扣
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;
    }


}
bubuko.com,布布扣

java 拷贝功能

原文:http://www.cnblogs.com/ytfcz/p/3533198.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!