Demonstrating the Bug: A Step-by-Step Example
What you'll learn: You'll see exactly how overriding equals without hashCode causes HashMap to malfunction with a concrete, reproducible example.
The Setup
Let's walk through a real scenario that breaks HashMap. Imagine you create a Person class and override only equals (ignoring hashCode):
class Person {
String name;
Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Person)) return false;
Person p = (Person) obj;
return this.name.equals(p.name);
}
// hashCode NOT overridden - uses Object's default!
}
The Bug in Action
HashMap<Person, String> map = new HashMap<>();
Person alice1 = new Person("Alice");
map.put(alice1, "Engineer");
Person alice2 = new Person("Alice");
// This returns null, even though equals says alice1.equals(alice2) is true!
String job = map.get(alice2);
System.out.println(job); // null
Why It Breaks
-
Inserting alice1:
HashMapcallsalice1.hashCode()(inherited fromObject) and gets some value, say12345. The entry goes into bucket 12345. -
Looking up with alice2:
HashMapcallsalice2.hashCode()(also fromObject) and gets a different value, say67890, becausealice2is a different object in memory. -
Wrong bucket searched:
HashMaplooks in bucket 67890, finds nothing, returnsnull—even thoughalice1.equals(alice2)istrue!
The contract violation means logically equal objects land in different buckets, making lookup fail.
Key Takeaway: Always override hashCode when overriding equals—otherwise hash-based collections will fail to find logically equal keys, even when they exist in the map.