equals() and hashCode() in Java — Why You Must Override Both
Overriding equals() without hashCode() breaks HashMap and HashSet behavior. Learn the contract between them and why they must be consistent.
Published September 22, 2026
If two objects are equal according to equals(), they must return the same hashCode(). Breaking that contract makes HashMap and HashSet lose objects, so always override both together.
The concept
Hash-based collections first use hashCode() to pick a bucket, then equals() to find the exact match inside it. If equal objects have different hash codes they land in different buckets and are never compared.
The default implementations use object identity, so two Point(1,2) instances are different unless you override.
HashMap lookup
- key.hashCode() chooses a bucket
- Inside the bucket, equals() compares candidates
- Match found → value returned
- Different hashCode for equal objects → wrong bucket → miss
Practical examples
Correct implementation
public final class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override public int hashCode() { return java.util.Objects.hash(x, y); }
}The bug when hashCode is missing
Set<Point> set = new HashSet<>();
set.add(new Point(1, 2));
set.contains(new Point(1, 2)); // false without hashCode()Records do it for you
record Point(int x, int y) {}Common mistakes
- Overriding equals but not hashCode.
- Using mutable fields in hashCode and then changing them while the object is in a HashSet.
- Comparing with == instead of equals() for objects.
Key takeaways
- Equal objects must share a hash code.
- Use Objects.equals and Objects.hash.
- Prefer records or Lombok to avoid boilerplate.
FAQ
Can different objects share a hash code?
Yes, that is a collision and is allowed; equals() resolves it.
Do I need both for TreeMap?
TreeMap uses compareTo/Comparator instead, but keep equals consistent.