一种使用字符串和整数键管理多维数组的简单方法



我对Java还很陌生,所以我必须依赖这个社区。

我需要将对象存储在某种数组/列表中,在那里我可以使用字符串和两个整数键快速访问对象。类似a["string"][1][1]的东西——我看过一些不同的指南和教程,但没能想出一个好的、易于管理的解决方案。

我正在创建一个Minecraft插件,我需要跟踪worldchunk_xchunk_z中特定块的位置。我正在尝试创建一种方法,在该方法中,我可以提供一个位置,该位置具有前面提到的三个值,并根据世界和块进行快速查找,因此我不必迭代世界中所有存储的块,但可以将其限制为世界的9个块。(我所在的当前区块和周围的所有邻居(

这个怎么样:

Map<String, Object[][]> store;

它必须是多维数组吗?您可以只使用一个带有自定义键的哈希映射,该自定义键包含字符串键和两个整数键。以下是我的意思的完整示例:

import java.util.HashMap;
import java.util.Objects;
public class multidim {
static class Key {
int index0, index1;
String str;
int _hash_code;
public Key(String s, int i0, int i1) {
_hash_code = Objects.hash(s, i0, i1);
str = s;
index0 = i0;
index1 = i1;
}
public int hashCode() {
return _hash_code;
}
public boolean equals(Object x) {
if (this == x) {
return true;
} else if (x == null) {
return false;
} else if (!(x instanceof Key)) {
return false;
}
Key k = (Key)x;
return (index0 == k.index0)
&& (index1 == k.index1)
&& Objects.equals(str, k.str);
}
}
public static void main(String[] args) {
HashMap<Key, Double> m = new HashMap<Key, Double>();
m.put(new Key("mjao", 3, 4), 119.0);
m.put(new Key("katt$k1t", 4, 6), 120.0);
System.out.println("Value that we put before: "
+ m.get(new Key("mjao", 3, 4)));
}
}

我们定义了一个类Key,它表示用于访问元素的值,并覆盖了它的equalshashCode方法,以便它可以在哈希映射中使用。然后我们将它与java.util.HashMap类一起使用。运行上述程序将输出Value that we put before: 119.0

编辑:在equals中添加this == x比较(一个小的优化(。

Map和Pair的组合怎么样?

Map<String, Pair<Integer, Integer>> tripletMap = new HashMap<>;
tripletMap.put(Pair.with(23, 1););

您可以将三元组中的值作为任何映射进行访问,然后将Pair检索为:

Pair<Integer, Integer> myPair = tripletMap.get("key")
myPair.getValue0()
myPair.getValue1()

最新更新