The HashMap Contract: equals and hashCode Must Agree
What you'll learn: Why HashMap requires equals and hashCode to work together consistently, or risk losing your data.
The Core Problem
You've learned that HashMap uses hashCode to organize objects into "buckets" for fast lookup, and equals to confirm exact matches. But here's the critical rule: if two objects are equal according to equals, they must produce the same hashCode.
If you break this contract, HashMap will malfunction — sometimes spectacularly.
Why HashMap Depends on Both
Imagine a library where books are sorted into sections by their first letter (the hash code), then you search within that section by full title (equals). Now imagine two identical books: one says its first letter is "M" and the other says "P". You'd put them in different sections, and when searching for one, you'd never find the other — even though they're the same book!
HashMap works the same way:
- It uses
hashCodeto find the right bucket - It uses
equalsto find the exact entry within that bucket
If equals says two keys are the same but their hashCode values differ, they'll be stored in different buckets. When you search for one, HashMap looks in the wrong bucket and finds nothing.
The Consequence
// BAD: equals says they're equal, hashCode doesn't agree
map.put(brokenKey1, "value"); // Goes to bucket #5
map.get(brokenKey2); // Looks in bucket #17, finds nothing!
// Even though brokenKey1.equals(brokenKey2) == true
Your data effectively disappears.
Key Takeaway: Always override equals and hashCode together, ensuring equal objects produce identical hash codes. This contract is non-negotiable for correct HashMap behavior.