Java hashCode 不适用于 HashMap?

Java hashCode doesn#39;t work with HashMap?(Java hashCode 不适用于 HashMap?)

本文介绍了Java hashCode 不适用于 HashMap?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 HashMap 实现一个稀疏网格,但是似乎覆盖 hashCode() 并不能完全按照我的预期工作.我将我的问题归结为以下代码:

I'm attempting to implement a sparse grid using HashMap, however it seems that overriding hashCode() doesn't work quite how I expect. 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)));
    }
}

我希望输出是:

A

但是,输出是:

null

两个new Coord(0, 0)"实例都应该返回相同的 hashCode(),但它似乎不像我预期的那样工作.为什么它没有按我的预期工作?

Both the "new Coord(0, 0)" instances should return the same hashCode(), but it doesn't seem to work how I expected. Why doesn't it work as I expect?

推荐答案

一个 HashMap 不能单独在 hashCode 上工作.它也依赖于 equals.

A HashMap cannot work on hashCode alone. It relies on equals as well.

为了解释原因,让我们考虑一个 HashMap<String, ?>.假设一个人有无限的内存,一个人可以为这个映射创建无限数量的键,但只有 430 万左右可能的哈希码(可能的 int 的数量).因此,会有碰撞.这就是为什么需要 equals 以确保我们获得正确键的值.

To explain why, let's consider a 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 ints). 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.

这篇关于Java hashCode 不适用于 HashMap?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Java hashCode 不适用于 HashMap?

基础教程推荐