Member-only story
The Golden Rule of Java: Why You Must Override hashCode() When You Override equals()
In Java, the relationship between the equals() and hashCode() methods is a fundamental contract. Breaking it can lead to baffling bugs, especially when your objects are stored in collections like HashSet or HashMap. The rule is simple: if you override one, you must override the other. Let's explore why this isn't just a suggestion, but a necessity.
The Short Answer
When you place objects into a hash-based collection like a HashSet or HashMap, the collection uses hashCode() first as a quick filter to place the object into a "bucket." It only uses the more expensive equals() method to check for true equality against other objects within that same bucket.
- If you only override
equals(): Two objects you consider equal will returntruefromequals(), but they will likely have different hash codes from the defaultObjectclass implementation. TheHashSetwill place them in different buckets and never bother callingequals(), leading it to believe they are two distinct objects. - If you only override
hashCode(): Two objects might have the same hash code, placing them in the same bucket. However, the defaultequals()method (which just compares memory addresses) will returnfalse. The collection will correctly assume they are…









