Java equals and hashCode: the contract and why HashMap depends on it
What == really compares, how to write equals and hashCode correctly, why breaking the contract makes HashSet lose objects, and the shortcuts that do it for you.
== and equals look interchangeable until a HashSet "loses" an object you just added. The fix
is a short contract every Java developer should know by heart.
== compares references, equals compares meaning
String a = new String("Lisbon");
String b = new String("Lisbon");
a == b; // false: two different objects
a.equals(b); // true: same charactersFor primitives (int, double, char), == compares values. For objects, including String,
Integer and your own classes, use equals.
The contract
If you override equals, it must be:
- Reflexive:
x.equals(x)is true. - Symmetric:
x.equals(y)exactly wheny.equals(x). - Transitive: if
x.equals(y)andy.equals(z), thenx.equals(z). - Consistent: same answer every time while the objects don't change.
x.equals(null)is false.
And the rule that collections depend on: equal objects must have equal hash codes. (Unequal objects may share a hash code; that's just a collision.)
Writing them by hand
import java.util.Objects;
public final class Booking {
private final String patientId;
private final LocalDate day;
public Booking(String patientId, LocalDate day) {
this.patientId = patientId;
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Booking)) return false;
Booking other = (Booking) o;
return patientId.equals(other.patientId) && day.equals(other.day);
}
@Override
public int hashCode() {
return Objects.hash(patientId, day);
}
}Use the same fields in both methods. Objects.hash and Objects.equals handle null fields
for you.
What breaks without hashCode
Set<Booking> bookings = new HashSet<>();
bookings.add(new Booking("p1", LocalDate.of(2026, 3, 1)));
bookings.contains(new Booking("p1", LocalDate.of(2026, 3, 1)));
// false if hashCode isn't overridden: the lookup searches the wrong bucketDon't mutate keys
If a field used in hashCode changes after the object is in a HashSet or used as a HashMap
key, the object sits in a bucket for its old hash. contains and remove then fail. Make key
classes immutable: final fields, no setters.
Shortcuts
- IDEs generate both methods from the fields you choose.
- Records (Java 16+) generate
equals,hashCodeandtoStringautomatically:record Booking(String patientId, LocalDate day) {}. The courses use Java 11, so you'll write them by hand there. - Lombok's
@EqualsAndHashCodeis common in older codebases.
Common mistakes
equals(Booking other)instead ofequals(Object o): that overloads rather than overrides, so collections never call it.@Overridecatches this at compile time.- Using
getClass() != o.getClass()in some classes andinstanceofin others, which breaks symmetry with subclasses.
This is core material in Java Intermediate.
Questions and answers
- Why must I override hashCode when I override equals?
- HashMap and HashSet first use hashCode to find the bucket, then equals to compare within it. If two equal objects have different hash codes, they land in different buckets and the collection never finds the match.
- Why does == work for small Integers but not large ones?
- Java caches Integer objects from -128 to 127, so autoboxed small values share an object and == happens to be true. Larger values are separate objects, so == compares references and returns false. Always use equals for objects.
Practise it
Read next
- Java collections: choosing between List, Set, Map and Deque
ArrayList vs LinkedList, HashMap vs TreeMap, HashSet vs LinkedHashSet, ArrayDeque for stacks and queues: what each costs and which to reach for first.
- Java interfaces vs abstract classes: when to use which
What interfaces and abstract classes are each for, default methods, composition over inheritance, and how interfaces make Java code easy to test.