返回一个新的 HashMap 实例

Returning a new instance of HashMap

我有一个存储自定义对象并将其映射到 class 中的某个 ArrayList 的 HashMap。我的 class 与另一个 class 通信(想想 MVC 风格)并传递该哈希图的副本。所以,在我的 "model" 中,我会:

public Map<AbstractArtistry, ArrayList<AbstractCommand>> getHashMap() {
    return new LinkedHashMap<AbstractArtistry, ArrayList<AbstractCommand>>(this.hashmap);
  }

然而,我的 "controller",当它得到它时,仍然可以编辑模型 this.hashmap 内部的 AbstractArtistries。为了避免这种情况,我是否必须一遍又一遍地创建一个抽象艺术的新实例,或者是否有更简洁的方法来做到这一点?意思是,我是否必须循环 model.hashmap.keySet(),为每个艺术性创建一个新实例,将其插入一个新的哈希图中(并对所有值执行相同的操作),然后 return 那个新的哈希图?或者有更简洁的方法吗?

您可以使用流来复制地图并将键替换为防御副本:

this.hashmap.entrySet()
    .stream()
    .collect(Collectors.toMap(e -> createCopy(e.getKey()), Map.Entry::getValue))

如果您还需要复制这些值,您可以 运行 通过类似的函数复制它们:

ArrayList<AbstractCommand> copyList(ArrayList<AbstractCommand> list) {
    return list.stream()
        .map(c -> copyCommand(c))
        .collect(Collectors.toCollection(ArrayList::new));
}