Java HashMap

huangapple go评论78阅读模式
英文:

Java HashMap<int[], Integer>

问题

我想将一个数组映射到一个 ArrayList,使得如果两个数组相同,它们映射到相同的东西。

这段代码输出 null

HashMap&lt;int[], Integer&gt; map = new HashMap&lt;&gt;();
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&lt;int[], Integer&gt; map = new HashMap&lt;&gt;();
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不起作用的原因是因为数组不基于数组内容实现hashCodeequals方法,而是基于对象标识。


Arrays.compareJava 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&lt;int[], Integer&gt; map = new TreeMap&lt;&gt;(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&lt;int[]&gt; arrayComparator = (a, b) -&gt; {
    for (int i = 0; i &lt; 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);
};

huangapple
  • 本文由 发表于 2020年8月11日 11:03:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63350890.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定