gpt4 book ai didi

Java Hashmap如何处理单词网格的键冲突

转载 作者:行者123 更新时间:2023-11-30 01:44:25 25 4
gpt4 key购买 nike

我有 100*100 维度的单词网格,这意味着字符会重复自己,我想将我的单词网格放入 HashMap 中以便更快地搜索。当键(字符)不在 HashMap 中时,我将其作为键添加到 HashMap 中,值是字符在网格中的行和列(位置),但是现在当有多个时我该如何处理人物?例如,“a”已经在 HashMap 中,但网格中的不同行和列位置中还有另一个“a”,我也想添加它,如何实现此目的以获得最佳性能?我绝对需要使用 HashMap

最佳答案

Minh 提供的上述链接提供了很好的概述。

如果你不想或者不能使用外部api,可以勾选以collection为值的选项:

//Let's say Pos handle your grid coordinates
class Pos {
int line, col;
...
}
...
// You may define the map as
Map<String, List<Pos>> myGrid = new HashMap<>();
...
// And for a given key and pos - in a loop e.g
String key = ... // e.g "a"
Pos pos = ... // e.g {0, 0}
myGrid.computeIfAbsent(key, k->new ArrayList<>()).add(pos);

根据需要,您还可以使用 Set-HashSet 代替 List-ArrayList。

干杯!

关于Java Hashmap如何处理单词网格的键冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58653140/

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