有几种选择:
2个维度
地图的地图
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()
and hashCode()
这里至关重要。然后你只需使用:
Map<Key, V> map = //...
and:
map.get(new Key(2, 5));
Table来自番石榴
Table<Integer, Integer, V> table = HashBasedTable.create();
//...
table.get(2, 5);
Table
uses 地图的地图下。
N 维
请注意,特别Key
class 是唯一可以扩展到 n 维的方法。您也可以考虑:
Map<List<Integer>, V> map = //...
但从性能角度以及可读性和正确性的角度来看,这很糟糕(没有简单的方法来强制列表大小)。
也许看看 Scala,其中有元组和case
类(替换整个Key
类与单行)。