在 java 中重写 hashmap 的键对象时,必须同时重写 equals() 和 hashcode() 方法。仅重写 equals() 会导致逻辑相等但哈希值不同的对象被存入不同的桶中,从而引发数据丢失或无法检索的问题。

为什么只重写 equals 会破坏 HashMap 的行为
如果只重写 equals() 而不重写 hashCode(),两个逻辑上相等的键对象可能拥有不同的哈希码。这会导致它们在 HashMap 的不同桶(Bucket)中,使得后续的 get() 操作无法找到已存储的值。

import java.util.HashMap;
public class BadKey {
private final String name;
public BadKey(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof BadKey)) return false;
BadKey other = (BadKey) o;
return name.equals(other.name);
}
// 忘记重写 hashCode()
}
public class Main {
public static void main(String[] args) {
HashMap<badkey string> map = new HashMap();
BadKey key1 = new BadKey("Alice");
map.put(key1, "Value1");
BadKey key2 = new BadKey("Alice");
System.out.println(map.get(key2)); // 输出 null,因为 hashCode 不同
}
}</badkey>
如何正确实现 equals 和 hashCode 契约
正确的做法是确保:equals() 返回 true 的两个对象,其 hashCode() 必须相等。通常使用 java.util.Objects.hash() 或 IDE 自动生成代码来保证这一点。

import java.util.HashMap;
import java.util.Objects;
public class GoodKey {
private final String name;
public GoodKey(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof GoodKey)) return false;
GoodKey other = (GoodKey) o;
return Objects.equals(name, other.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
public class Main {
public static void main(String[] args) {
HashMap<goodkey string> map = new HashMap();
GoodKey key1 = new GoodKey("Bob");
map.put(key1, "Value2");
GoodKey key2 = new GoodKey("Bob");
System.out.println(map.get(key2)); // 输出 Value2
}
}</goodkey>
可变字段对 HashMap 键的影响
如果键对象的字段在放入 HashMap 后被修改,会导致 hashCode() 改变,从而使该对象无法被再次找到。因此,用作 HashMap 键的对象应当是不可变的,或者其参与 equals 和 hashCode 计算的字段在对象生命周期内保持不变。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











