java - 实体类里浅拷贝 与 深拷贝

1.背景

 

 因为存在集合类 ,因此引出了浅拷贝与深拷贝,

浅拷贝无法将  List<TreeData>  这样的指定栈堆 的类型字段 new一个新的地址,需要使用深拷贝才能解决

2.浅拷贝

  @Note("克隆对象")
    public TreeData cloneTd() {
        TreeData td = null;
        try {
            td = (TreeData) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new CustomResultException(ResultEn.ENTITY_CLONE_ERR.getCode(), ResultEn.ENTITY_CLONE_ERR.getMessage()
                    + ":" + ExcBox.getExcMsg(e));
        }
        if (null == td) throw new CustomResultException(ResultEn.ENTITY_CLONE_ERR);
        return td;
    }

3.深拷贝【存在bug且线程不安全】

@Note("克隆对象")
    public TreeData cloneTd() {
        TreeData td = new TreeData(planGid, pGid, name, valu, isObj, level, sort, vueType, enums, isMust,
                isInherit, isOCR, isMulFile, lcTm, null);
        List<TreeData> children = new ArrayList<>();
        System.arraycopy(this.children, 0, children, 0,this.children.size()); 
     td.setChildren(children);
     
return td;
  }

仍然有缺点,只能深入到实体里的第一个  List<TreeData> children  

3.深拷贝解决

要么使用递归一层一层克隆,要么使用json转换处理,都会开辟新的栈堆

 

posted @ 2022-09-07 17:42  岑惜  阅读(631)  评论(0)    收藏  举报