如何创建具有两个键(键对、值)的 HashMap? [英] How to create a HashMap with two keys (Key-Pair, Value)?
问题描述
我有一个二维整数数组.我希望将它们放入 HashMap 中.但我想根据数组索引访问 HashMap 中的元素.类似的东西:
I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like:
对于 A[2][5],map.get(2,5)
返回与该键关联的值.但是如何使用一对键创建 hashMap 呢?或者一般来说,多个键: Map<((key1, key2,..,keyN), Value)
以我可以使用 get(key1,key2,...键N).
For A[2][5], map.get(2,5)
which returns a value associated with that key. But how do I create a hashMap with a pair of keys? Or in general, multiple keys: Map<((key1, key2,..,keyN), Value)
in a way that I can access the element with using get(key1,key2,...keyN).
发布问题 3 年后,我想添加更多内容
我遇到了 NxN 矩阵
的另一种方法.
I came across another way for NxN matrix
.
数组索引,i
和 j
可以表示为单个 key
如下:
Array indices, i
and j
can be represented as a single key
the following way:
int key = i * N + j;
//map.put(key, a[i][j]); // queue.add(key);
并且可以通过这种方式从 key
检索索引:
And the indices can be retrevied from the key
in this way:
int i = key / N;
int j = key % N;
推荐答案
有几个选项:
Map<Integer, Map<Integer, V>> map = //...
//...
map.get(2).get(5);
包装键对象
public class Key {
private final int x;
private final int y;
public Key(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Key)) return false;
Key key = (Key) o;
return x == key.x && y == key.y;
}
@Override
public int hashCode() {
int result = x;
result = 31 * result + y;
return result;
}
}
实现 equals()
和 hashCode()
在这里至关重要.然后你只需使用:
Implementing equals()
and hashCode()
is crucial here. Then you simply use:
Map<Key, V> map = //...
和:
map.get(new Key(2, 5));
Table
来自 Guava
Table<Integer, Integer, V> table = HashBasedTable.create();
//...
table.get(2, 5);
Table
使用 map of maps 下面.
请注意,特殊的 Key
类是唯一可扩展到 n 维的方法.您还可以考虑:
Notice that special Key
class is the only approach that scales to n-dimensions. You might also consider:
Map<List<Integer>, V> map = //...
但从性能角度以及可读性和正确性的角度来看,这很糟糕(没有简单的方法来强制执行列表大小).
but that's terrible from performance perspective, as well as readability and correctness (no easy way to enforce list size).
也许看看 Scala,那里有元组和 case
类(用单行替换整个 Key
类).
Maybe take a look at Scala where you have tuples and case
classes (replacing whole Key
class with one-liner).
这篇关于如何创建具有两个键(键对、值)的 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!