• java 拷贝功能


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

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

    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;
        }
    
    
    }
  • 相关阅读:
    浏览器内核
    gulp菜鸟级零基础详细教程
    Mysql自连接的一些用法
    ListView和Adapter数据适配器的简单介绍
    Android轮播图
    css-flex布局知识梳理
    JavaScript 复杂判断的更优雅写法
    团队合作前端书写习惯总结
    常见的HTTP报头(头参数)
    常见的HTTP状态码
  • 原文地址:https://www.cnblogs.com/ytfcz/p/3533198.html
Copyright © 2020-2023  润新知