Java hashCode 不适用于 HashMap?

2024-08-24Java开发问题
3

本文介绍了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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13