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转换处理,都会开辟新的栈堆
本文来自博客园,作者:岑惜,转载请注明原文链接:https://www.cnblogs.com/c2g5201314/p/16666644.html
响应开源精神相互学习,内容良币驱除劣币

浙公网安备 33010602011771号