Java Hashmap如何处理单词网格的键冲突 [英] Java Hashmap how to handle key collision for grid of words
问题描述
我有100 * 100维度的单词网格,这意味着字符会重复,我想将我的单词网格放入哈希图中以加快搜索速度.当键(字符)不在哈希图中时,我将其作为键添加到哈希图中,并且值是网格中字符的行和列(位置),但是现在当有多个键时,我该如何处理人物?例如,哈希图中已经有一个"a",但是在网格中有另一个"a"位于不同的行和列位置),我也想添加它,如何才能达到最佳性能呢?我绝对需要使用哈希图
I have grid of words of 100*100 dimensions, this means characters repeat themselves, I want to put my grid of words into a hashmap for faster searching. When the key (character) isn't in the hashmap, I add it in to the hashmap as key and the value is the line and column (the position) of the character in the grid, but now how can I handle when there's multiple characters? For example, "a" is already in the hashmap, but there's another "a" in a different line and column position) in the grid, I want to add it also, how can I accomplish this for best performance? I absolutely need to use a hashmap
推荐答案
Minh提供的上述链接提供了很好的概述.
The above link provided by Minh provides a good overview.
如果您不想或不能使用外部api,则可以将collection作为值来检查选项:
If you don't want or can't use external apis, you can check the option with collection as value:
//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.
You may also use a Set-HashSet instead of List-ArrayList depending on your need.
干杯!
这篇关于Java Hashmap如何处理单词网格的键冲突的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!