“Why must you override hashCode when you override equals?” is one of the most common Java interview questions. The answer is a rule called the equals and hashCode contract, and breaking it causes bugs that are hard to find.
What equals means
The default equals() compares object references: two objects are equal only if they are the same object. For value objects such as a Student with an id and a name, you usually want equality based on the fields instead.
The contract
- If
a.equals(b)is true, thena.hashCode() == b.hashCode()must also be true. - The hash code must not change while the object is used as a key.
- Equal objects must always give equal results when compared again (consistency).
The reverse is not required: equal hash codes do not guarantee equal objects, which is why collisions happen.
Why HashMap needs it
A HashMap uses hashCode() to choose a bucket, then equals() to find the exact key. If you override only equals(), two “equal” students may land in different buckets, so get() returns null even though you just stored the key.
A correct example
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student s = (Student) o;
return id == s.id;
}
@Override
public int hashCode() {
return Objects.hash(id);
}
Use the same fields in both methods. Java records and IDE generators do this correctly for you.
Common mistakes
- Overriding one method without the other.
- Using mutable fields in hashCode, then changing the object while it sits in a HashSet.
- Including fields in equals that the business does not consider part of identity.
Related: how a Java HashMap works and Java records for beginners.
These topics are practised with projects and mock interviews in our Java Full Stack course in Bangalore.
Book a free demo class at our BTM Layout centre, and ask a counsellor for batch details.
