【问题标题】:Will there still be aliasing after I run my copy methods?运行复制方法后还会有别名吗?
【发布时间】:2017-08-23 21:22:53
【问题描述】:

我有一张地图,其中地图作为值,地图集作为值(在 java 中)。我为每个人编写了一个方法来复制它们,并尽量避免出现别名,但是我的程序的行为方式,我不确定它们是否有效。

private Map<String, Set<String>> deepCopySet(Map<String, Set<String>> ruledOutCount) {
    Map<String,Set<String>> copy = new HashMap<String,Set<String>>();
    for(Map.Entry<String, Set<String>> entry : ruledOutCount.entrySet())
    {
        copy.put(entry.getKey(), new HashSet<String>(entry.getValue()));
    }
    return copy;
}

private Map<SG, Map<classObj, Integer>> deepCopyMap(Map<SG, Map<classObj, Integer>> classCountPerSG) 
{
    Map<SG,Map<classObj,Integer>> copy = new HashMap<SG,Map<classObj,Integer>>();
    for(Map.Entry<SG, Map<classObj,Integer>> entry : classCountPerSG.entrySet())
    {
        copy.put(entry.getKey(), new HashMap<classObj,Integer>(entry.getValue()));
    }
    return copy;
}

classObj 和 SG 是我自己的对象。 运行这些复制方法后是否有任何别名? 谢谢。

【问题讨论】:

  • “但顺便说一下我的程序的行为方式,我不确定它们是否有效。”你希望它做什么,它会做什么?

标签: java deep-copy


【解决方案1】:

deepCopySet 方法看起来不错。

deepCopyMap 方法也可以,但它取决于SGclassObj 的类型:如果它们也可能是映射(或其他复杂对象),您可能会得到浅拷贝。

请注意,Java 仅在编译时进行类型检查!所以在下面的代码中

StringBuilder willNotBeCopied = new StringBuilder();
Map evil = new HashMap();
evil.put("a", new HashSet(Arrays.asList(willNotBeCopied)));
Map shallowCopy = deepCopySet(evil);
willNotBeCopied.append("some text");

shallowCopy 映射将包含相同的 StringBuilder 实例(浅拷贝)。

【讨论】:

  • 谢谢!这两个对象都只存储字符串和整数,所以应该没问题
猜你喜欢
  • 2017-05-19
  • 2016-05-07
  • 1970-01-01
  • 2015-12-12
  • 2017-04-07
  • 1970-01-01
  • 2021-02-10
  • 2019-07-06
  • 1970-01-01
相关资源
最近更新 更多