简体   繁体   English

Java hashCode 不适用于 HashMap?

[英]Java hashCode doesn't work with HashMap?

I'm attempting to implement a sparse grid using HashMap, however it seems that overriding hashCode() doesn't work quite how I expect.我正在尝试使用 HashMap 实现一个稀疏网格,但是似乎覆盖 hashCode() 并没有像我期望的那样工作。 I've boiled down my issue to the following code:我已将我的问题归结为以下代码:

public class Main {

private static class Coord {
    int x, y;

    public Coord(int x, int y) {
        this.x = x;
        this.y = y;
        }

        @Override
        public int hashCode() {
            // See https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function
            return (((x + y) * (x + y + 1)) / 2) + y;
        }
    }

    public static void main(String[] args) {
        HashMap<Coord, String> grid = new HashMap<Coord, String>();
        grid.put(new Coord(0, 0), "A");
        System.out.println(grid.get(new Coord(0, 0)));
    }
}

I'm expecting the output to be:我期待输出是:

A

However, the output is:但是,输出是:

null

Both the "new Coord(0, 0)" instances should return the same hashCode(), but it doesn't seem to work how I expected.两个“new Coord(0, 0)”实例都应该返回相同的 hashCode(),但它似乎不像我预期的那样工作。 Why doesn't it work as I expect?为什么它不像我期望的那样工作?

A HashMap cannot work on hashCode alone. HashMap不能单独处理hashCode It relies on equals as well.它也依赖于equals

To explain why, let's consider a HashMap<String, ?> .为了解释原因,让我们考虑一个HashMap<String, ?> Supposing for a second that one has infinite memory, one can create an infinite number of keys for this map, but only 4.3 million or so possible hash codes (the number of possible int s).假设一个人拥有无限内存,可以为这个映射创建无限数量的键,但只有 430 万个左右可能的哈希码(可能的int数量)。 Thus, there will be collisions.这样,就会发生碰撞。 This is why equals is required in order to make sure that we're getting the value for the correct key.这就是为什么需要equals以确保我们获得正确键的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM