In Java you override hashCode whenever you override equals because the contract says that equal
objects must have equal hash codes, and every hash-based collection relies on it. Break that rule
and a HashMap looks in the wrong place: map.get(key) returns null for a key that is “equal” to
one already in the map, and a HashSet happily stores duplicates. Nothing throws. The data is
simply not found.
Below are two short programs that show the failure, followed by the way to write both methods so it cannot happen.
What is the equals and hashCode contract in Java?
The Javadoc of Object.equals
asks for an equivalence relation. In plain words:
- Reflexive: an object equals itself.
- Symmetric: if
a.equals(b), thenb.equals(a). - Transitive: if
a.equals(b)andb.equals(c), thena.equals(c). - Consistent: the answer does not change unless a field used in the comparison changes.
a.equals(null)isfalse.
Object.hashCode
adds three rules:
- The value stays the same during one run of the program, as long as no field used in
equalschanges. - Equal objects must return the same hash code.
- Unequal objects may share a hash code. Distinct values are better for performance, but they are not required.
The arrow points one way only. Equal objects imply equal hashes; equal hashes imply nothing.
How does HashMap use hashCode and equals?
A HashMap
is a hash table: an array of buckets. The lookup has two steps.
hashCode()of the key decides which bucket to look in.- Inside that bucket,
equalsdecides whether a stored key is the one you asked for.
That is why get and put take constant time when the hash function spreads the keys well across
the buckets. It is also why the contract matters: step 2 never happens for an entry that sits in a
different bucket. The Map documentation says openly that an implementation may skip equals
after comparing hash codes, because objects with different hash codes cannot be equal.
HashSet behaves the same way, because it is backed by a HashMap.
What happens if you override equals but not hashCode?
Point below defines equality by its coordinates and forgets hashCode:
static final class Point {
private final int x;
private final int y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
return o instanceof Point other && x == other.x && y == other.y;
}
// no hashCode()
}
public static void main(String[] args) {
Point a = new Point(1, 2);
Point b = new Point(1, 2);
System.out.println("a.equals(b): " + a.equals(b));
Map<Point, String> labels = new HashMap<>();
labels.put(a, "start");
System.out.println("get(a): " + labels.get(a));
System.out.println("get(b): " + labels.get(b));
Set<Point> points = new HashSet<>();
points.add(a);
points.add(b);
System.out.println("set size: " + points.size());
}
Output on JDK 25:
a.equals(b): true
get(a): start
get(b): null
set size: 2
a and b are equal, yet the map does not find the value under b, and the set holds both.
Point still inherits hashCode from Object, which returns distinct integers for distinct
objects as far as is reasonably practical. So b is searched for under a different hash than the
one a was stored with, and your equals is never asked.
The compiler can catch this. With javac -Xlint:overrides the same file produces:
warning: [overrides] Class Point overrides equals, but neither it nor any superclass overrides hashCode method
What happens when you change a key after putting it in a HashMap?
A correct pair of methods is not enough if the key can change. User here follows the contract,
but email is mutable:
static final class User {
private String email;
User(String email) {
this.email = email;
}
void setEmail(String email) {
this.email = email;
}
@Override
public boolean equals(Object o) {
return o instanceof User other && Objects.equals(email, other.email);
}
@Override
public int hashCode() {
return Objects.hashCode(email);
}
}
public static void main(String[] args) {
User user = new User("ann@example.com");
Map<User, String> roles = new HashMap<>();
roles.put(user, "admin");
user.setEmail("ann@corp.example");
System.out.println("get(user): " + roles.get(user));
System.out.println("get(old email): " + roles.get(new User("ann@example.com")));
System.out.println("size: " + roles.size());
System.out.println("values: " + roles.values());
}
get(user): null
get(old email): null
size: 1
values: [admin]
The entry is still in the map, and no key can reach it. Looking up user fails because its hash
code changed, so the search goes to the wrong place. Looking up the old email finds the right
place, but equals compares against the stored key, which now holds the new email.
The Map documentation
warns about exactly this: the behaviour of a map is not specified if a key changes in a way that
affects equals while it is in the map. The practical rule is stricter and easier to follow: build
keys from final fields.
How to implement equals and hashCode correctly
Use the same fields in both methods, and let java.util.Objects handle null:
static final class Point {
private final int x;
private final int y;
private final String label;
Point(int x, int y, String label) {
this.x = x;
this.y = y;
this.label = label;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
return o instanceof Point other
&& x == other.x
&& y == other.y
&& Objects.equals(label, other.label);
}
@Override
public int hashCode() {
return Objects.hash(x, y, label);
}
}
instanceof with a pattern variable is false for null, so the null check comes for free.
Objects.equals(a, b) is true when both are null and never throws. Objects.hash(...) combines
several fields; for a single field use Objects.hashCode(field), since Objects.hash with one
argument does not return that argument’s own hash code.
getClass or instanceof in equals?
Both are defensible, and the difference only shows up with inheritance. With instanceof, a
subclass instance can equal a superclass instance. That is fine until a subclass adds a field to
its own equals: then point.equals(colorPoint) is true while colorPoint.equals(point) is
false, and symmetry is gone. Comparing getClass() keeps symmetry by declaring that objects of
different classes are never equal, at the price of rejecting subclasses that add no state at all.
My preference: make value classes final and use instanceof. With no subclasses there is no
dilemma.
Do records generate equals and hashCode?
Yes. A record
gets equals, hashCode and toString derived from all of its components, and two records
created from the same components are guaranteed to have the same hash code.
record Coordinate(int x, int y) {}
Map<Coordinate, String> labels = new HashMap<>();
labels.put(new Coordinate(1, 2), "start");
System.out.println(labels.get(new Coordinate(1, 2))); // start
Record fields are final, which also removes the mutated-key problem, provided the components
themselves are immutable. For a small value used as a map key, a record is the default choice.
equals and hashCode for JPA entities
Entities are the awkward case. A database-generated id is null until the entity is saved, so a
hashCode based on the id changes at that moment. An entity added to a HashSet before saving is
then lost in the same way as the mutated key above. Two approaches work:
- Base both methods on a business key that is set at construction and never changes, such as an ISBN or an order number.
- If the generated id is all you have, compare ids only when they are not
nulland return a constant fromhashCode:
@Override
public boolean equals(Object o) {
if (this == o) return true;
return o instanceof Order other
&& id != null
&& id.equals(other.getId());
}
@Override
public int hashCode() {
return Order.class.hashCode();
}
A constant hash is legal, since unequal objects may share a hash code. It costs speed in large hash collections, which is rarely a concern for the handful of entities in one association. The Hibernate user guide describes both options.
The rules, in short
- Override
hashCodeevery time you overrideequals, using the same fields. - Equal objects must have equal hash codes. The reverse is not required.
- Never change a field used in
equalsorhashCodewhile the object is a key in a map or an element of a hash set. Preferfinalfields. - Use
Objects.equalsandObjects.hashinstead of hand-written null checks. - Make value classes
final, or use a record and write neither method. - For JPA entities, use a business key, or the id with a constant
hashCode. - Turn on
-Xlint:overridesso the compiler reports a missinghashCode.