Sitemap
CodeElevation

A gathering place for individuals passionate about coding — be it programmers, devs, or engineers.

Member-only story

The Golden Rule of Java: Why You Must Override hashCode() When You Override equals()

--

Press enter or click to view image in full size

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 return true from equals(), but they will likely have different hash codes from the default Object class implementation. The HashSet will place them in different buckets and never bother calling equals(), 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 default equals() method (which just compares memory addresses) will return false. The collection will correctly assume they are…

--

--

Seasoned software developer with 12+ years of experience, specializing in AI, DL/ML Engineering, Java, Spring Boot, Kafka, Redis, and system architecture.

CodeElevation
CodeElevation

Published in CodeElevation

A gathering place for individuals passionate about coding — be it programmers, devs, or engineers.