zoukankan      html  css  js  c++  java
  • 浅拷贝和深拷贝

    基本的拷贝是浅拷贝,只会拷贝基础类型的值,其他是属性引用拷贝,公用一个属性实例。

    重写clone进行深拷贝,不再拷贝引用直接拷贝数值。

    如何利用序列化来完成对象的拷贝呢?在内存中通过字节流的拷贝是比较容易实现的。把母对象写入到一个字节流中,再从字节流中将其读出来,这样就可以创建一个新的对象了,并且该新对象与母对象之间并不存在引用共享的问题,真正实现对象的深拷贝。

      
      //重写clone
      @Override
    public Object clone() throws CloneNotSupportedException { //将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝 try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); //将流序列化成对象 ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); } catch (Exception e) { throw new CloneNotSupportedException(e.getMessage()); } }
    public class CloneUtils {
    
        public static <T extends Serializable> T clone(T obj){
            T cloneObj = null;
            try {
                //写入字节流
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                ObjectOutputStream obs = new ObjectOutputStream(out);
                obs.writeObject(obj);
                obs.close();
                
                //分配内存,写入原始对象,生成新对象
                ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(ios);
                //返回生成的新对象
                cloneObj = (T) ois.readObject();
                ois.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return cloneObj;
        }
    }
  • 相关阅读:
    scm工作流部署问题解决
    mysql 数据库时间慢了8小时
    Vue加了二级路由后,跳转后js好像都失效
    flutter 莫名其妙错误集锦
    confluence-6.7.1 install
    git idea 项目复原
    springboot 本地jar发布,打war包
    flutter 初探2--点击按钮打开新窗口
    [转载]无法解决 equal to 操作中 "Chinese_PRC_CI_AS" 和 "Chinese_PRC_CI_AS_KS_WS" 之间的排序规则冲突
    [转载]天赋秉异的人永远是少数
  • 原文地址:https://www.cnblogs.com/wade-luffy/p/5741629.html
Copyright © 2011-2022 走看看