The equals-hashCode Contract: Core Requirement
What You'll Learn
You'll understand the fundamental rule linking equals() and hashCode(): equal objects must produce equal hash codes.
The Core Rule
When you override equals() in a class, you must also override hashCode() to maintain a critical contract: if two objects are equal according to equals(), they must return the same hashCode().
This is Java's most important consistency rule for object identity.
Why This Matters
Think of hashCode() as a quick numerical "zip code" for an object, and equals() as checking the full address. If two houses have the same full address (equal via equals()), they must also share the same zip code (hashCode()). However, two houses with the same zip code might still have different full addresses.
In code terms:
- If
obj1.equals(obj2)returnstrue, thenobj1.hashCode()must equalobj2.hashCode() - If
obj1.hashCode()equalsobj2.hashCode(),obj1.equals(obj2)may or may not betrue
The Consequence of Breaking This Contract
Hash-based collections like HashSet, HashMap, and Hashtable rely on this contract. They use hashCode() first to quickly locate where an object should be stored or found. If your equals() says two objects are identical but their hash codes differ, these collections will malfunction — they might store duplicates, fail to find existing objects, or behave unpredictably.
Key Takeaway: Always override hashCode() when you override equals(). Equal objects must produce equal hash codes, or hash-based collections will break.