英文:
Java HashMap<int[], Integer>
问题
我想将一个数组映射到一个 ArrayList
,使得如果两个数组相同,它们映射到相同的东西。
这段代码输出 null
:
HashMap<int[], Integer> map = new HashMap<>();
map.put(new int[1], 0);
System.out.println(map.get(new int[1]));
而我希望输出是 0
。有没有一种简单的方法可以做到这一点?我应该使用 TreeMap
吗?在 TreeMap
中如何实现这个目标?
英文:
I want to map an array to an ArrayList
such that two arrays mapped to the same thing if they are identical.
This outputs null
:
HashMap<int[], Integer> map = new HashMap<>();
map.put(new int[1], 0);
System.out.println(map.get(new int[1]));
And I want the output to be 0
. Is there an easy way to do this? Should I use TreeMap
? How do I do this in TreeMap
?
答案1
得分: 3
使用TreeMap
可以工作,如果您传入一个可以用于数组的Comparator
实例。幸运的是,标准库已经有一个您可以使用的方法 Arrays.compare
:
TreeMap<int[], Integer> map = new TreeMap<>(Arrays::compare);
map.put(new int[1], 1);
System.out.println(map.get(new int[1])); // 输出: 1
话虽如此,将可变对象(如数组)用作映射键不是一个很好的主意。如果您意外更改用作键的数组,映射将无法按预期工作。
HashMap
不起作用的原因是因为数组不基于数组内容实现hashCode
或equals
方法,而是基于对象标识。
Arrays.compare
在 Java 9 中添加。对于 Java 8,您需要自己编写Comparator
。以下是一个选项:
Comparator<int[]> arrayComparator = (a, b) -> {
for (int i = 0; i < Math.min(a.length, b.length); i++) {
int compare = Integer.compare(a[i], b[i]);
if (compare != 0) return compare;
}
return Integer.compare(a.length, b.length);
};
英文:
Using a TreeMap
works, if you pass in a Comparator instance that can be used with arrays. Luckily the standard library already has a method you can use Arrays.compare
:
TreeMap<int[], Integer> map = new TreeMap<>(Arrays::compare);
map.put(new int[1], 1);
System.out.println(map.get(new int[1])); // output: 1
That said, using a mutable object such as an array as the map key is not a very good idea. If you accidentally change an array used as a key, the map will stop working as expected.
The reason why HashMap
will not work is because arrays don't implement a hashCode
or equals
method based on the array contents. They are based on the object identity instead.
Arrays.compare
was added in Java 9. For Java 8 you'll need to write the Comparator
yourself. Here is one option:
Comparator<int[]> arrayComparator = (a, b) -> {
for (int i = 0; i < Math.min(a.length, b.length); i++) {
int compare = Integer.compare(a[i], b[i]);
if (compare != 0) return compare;
}
return Integer.compare(a.length, b.length);
};
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论