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 @   岑惜  阅读(611)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
点击右上角即可分享
微信分享提示