Java hashCode doesn#39;t work with 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 int
s). 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?
基础教程推荐
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 降序排序:Java Map 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01