gpt4 book ai didi

java - 保护 map 内容不被修改

转载 作者:行者123 更新时间:2023-12-02 05:00:44 25 4
gpt4 key购买 nike

我有一个 Map 类型的变量

Map<AiTile, List<AiTile>> result = new HashMap<AiTile, List<AiTile>>();

例如;我将几个 AiTile-List 插入 map 内,然后使用“clear”方法删除列表的内容。我想在删除列表内容时保护 map 内容,该怎么做?

最佳答案

Map.put(key, value) 添加对列表的引用,而不是实际的列表内容。如果我理解正确的话,您想在 map 中保留旧的列表值并删除原始列表的内容。

您可能想要将原始列表的副本而不是引用添加到 map 中。例如:

map.put(key, new ArrayList<AiTile>(originalList));

更新

如果您只想将键、值对添加到 map (仅当它们尚不存在时)并更新 map 中现有的列表,请使用 map.contains(key)list.addAll(anotherList):

// if no key is present
if (!map.containsKey(key)) {
// add key value pair
map.put(key, value);
} else {
// get the current list out of the map
// and merge it with the new one
map.get(key).addAll(value);
}

注意:根据定义,列表可以包含重复项。如果您想要合并两个列表之间的所有项目以使它们不包含重复项,您可能需要查看集合

>> java doc is your best friend

关于java - 保护 map 内容不被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20555712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com