Scrivio Interview library
ConceptFoundations6 min read · updated 12 November 2026

State the equals contract and the hashCode contract. What breaks in a HashMap if a class overrides equals but not hashCode?

equals must be reflexive, symmetric, transitive and consistent, and x.equals(null) must return false. hashCode must return equal values for equal objects, may return equal values for unequal objects, and must stay the same while the fields used by equals do not change. If a class overrides equals but not hashCode, equal keys usually get different hash codes, so a HashMap looks in the wrong bucket: get returns null for a logically equal key, and a HashSet ends up holding duplicates.

Why this question is asked

equals and hashCode are two of the oldest methods in Java, and they cause bugs in every generation of code, from hand-written value classes to JPA entities. Interviewers ask about the contracts because almost every collection and cache in the JDK relies on them, and a class that breaks them does not fail loudly; it just makes maps and sets behave strangely. In this answer, we will recap what the two methods are for, go through each rule of the equals contract and the hashCode contract with small examples, reproduce what goes wrong in a HashMap when hashCode is missing, and finish with the simple ways to implement both correctly.

1A Quick Recap of equals and hashCode

Every Java object inherits equals and hashCode from Object. By default, equals is identity: two references are equal only if they point to the same object. The default hashCode is a number derived from the object itself, usually different for every object. For entities with an identity, such as a service or a thread, that is exactly right.

For value classes, such as a Money amount or a Point, we usually want logical equality: two objects with the same contents should be equal. When we override equals to express that, we take on two contracts written in the Javadoc of Object, one for equals and one for hashCode, and the hash-based collections trust that we kept them.

2The equals Contract, Rule by Rule

The equals contract has five rules. They sound abstract, but each one exists because collections depend on it. The table shows what each rule means in plain words.

The five rules of equals
RuleMeaningExample
ReflexiveEvery object equals itselfx.equals(x) is true
SymmetricIf x equals y, y equals xa.equals(b) == b.equals(a)
TransitiveIf x equals y and y equals z, x equals zchains of equal objects agree
ConsistentSame answer every time while nothing changesno clocks or lookups inside equals
Non-nullNothing equals nullx.equals(null) is false, never throws
Collections rely on every rule; breaking one gives silent wrong answers.

Symmetry and transitivity are the rules most often broken, usually by subclasses that add a field or by classes that try to be equal to a different type, such as a CaseInsensitiveString that claims to equal a plain String. The String does not agree, so a.equals(b) is true while b.equals(a) is false, and a collection's answer then depends on which object it happens to call equals on. Consistency is broken by equals methods that depend on mutable or external state, such as the current time or a database lookup.

3The hashCode Contract

The hashCode contract has three parts. First, if two objects are equal according to equals, they must have the same hash code. Second, unequal objects are allowed to have the same hash code; that is a collision, and it only costs performance. Third, hashCode must return the same value each time it is called on the same object, as long as the fields used by equals have not changed.

Java
record Point(int x, int y) {}
new Point(1, 2).equals(new Point(1, 2)); // true
new Point(1, 2).hashCode() == new Point(1, 2).hashCode(); // true: required
"Aa".hashCode() == "BB".hashCode(); // true: 2112, a legal collision
"Aa".equals("BB"); // false

Notice that the rule only goes one way. Equal objects must share a hash code, but a shared hash code proves nothing about equality. That one-way rule is exactly what lets a HashMap use the hash code as a quick filter and then call equals to be sure.

4What Breaks in a HashMap Without hashCode

A HashMap uses the hash code to choose a bucket, an index into its internal array, and only then calls equals on the keys in that bucket. Let us see what happens with a class that overrides equals but keeps Object's hashCode.

Java
final class Sku {
private final String code;
Sku(String code) { this.code = code; }
@Override public boolean equals(Object o) {
return o instanceof Sku s && code.equals(s.code);
}
// hashCode not overridden
}
Map<Sku, Integer> stock = new HashMap<>();
stock.put(new Sku("A-1"), 10);
stock.get(new Sku("A-1")); // null (almost always)
Set<Sku> skus = new HashSet<>();
skus.add(new Sku("A-1"));
skus.add(new Sku("A-1"));
skus.size(); // 2: logical duplicates

The two Sku objects are equal, but their hash codes come from Object and are almost certainly different. So get computes a different bucket from the one put used, finds nothing there, and returns null without ever calling equals. The set has the same problem in reverse: add looks in the wrong bucket, finds no equal element, and stores a duplicate. Very occasionally the two hash codes happen to land in the same bucket and everything seems to work, which makes the bug even harder to find.

5Implementing Both Correctly

The simplest correct implementation uses the same fields in both methods, with the helpers in java.util.Objects to handle nulls.

Java
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Sku other)) return false; // also handles null
return Objects.equals(code, other.code);
}
@Override public int hashCode() {
return Objects.hash(code);
}
// Or let the compiler write both:
record Sku(String code) {}
new Sku("A-1").equals(new Sku("A-1")); // true
new HashSet<>(List.of(new Sku("A-1"), new Sku("A-1"))).size(); // 1

Notice that instanceof returns false for null, so the null rule comes for free. For a value class, a record is usually the best answer: it generates equals and hashCode from all its components, consistently, and it is immutable, so the hash code never changes while the object is in a set.

6Follow-up questions

Is it wrong to override hashCode but not equals?

It does not break the contract, because unequal objects may share a hash code, but it is pointless. Without equals, objects are still compared by identity, so two logically equal keys remain different keys. Override both or neither.

Why does Objects.hash cost a little more than a hand-written hashCode?

Objects.hash takes varargs, so each call creates an array and boxes primitive fields. That is fine for most classes. For a key used millions of times in a hot path, 31 * Long.hashCode(a) + b.hashCode() avoids the allocation.

What does consistent mean when an object is mutable?

equals and hashCode may change when the fields they use change; consistency only requires the same answer while those fields stay the same. The danger is changing those fields while the object sits in a HashSet or is used as a HashMap key, which leaves it in the wrong bucket.

7Conclusion

In this answer, we saw the five rules of equals, reflexive, symmetric, transitive, consistent and false for null, and the three parts of the hashCode contract: equal objects share a hash code, collisions are allowed, and the value stays stable while the fields do. We reproduced how a missing hashCode makes a HashMap look in the wrong bucket, so get returns null and a HashSet holds duplicates, and we saw that Objects.equals with Objects.hash, or a record, fixes it.

What to say in the interviewAbout 70 seconds aloud

Open with

The equals contract says equals must be reflexive, so x equals x; symmetric, so if x equals y then y equals x; transitive across chains; consistent, meaning the same answer every time as long as nothing relevant changes; and x.equals(null) must be false rather than throwing.

Then, if they want more

The hashCode contract says that equal objects must have equal hash codes, unequal objects may collide, which only costs performance, and the hash code must stay the same while the fields used by equals do not change. If a class overrides equals but not hashCode, it keeps Object's hashCode, which is different for practically every instance.

A HashMap picks the bucket from the hash code before it ever calls equals, so a lookup with a logically equal key goes to a different bucket and get returns null, and a HashSet happily stores two equal objects.

To avoid it, I use the same fields in both methods, Objects.equals and Objects.hash for a hand-written class, or, for value types, just a record, which generates both correctly and is immutable.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "State the equals contract and the hashCode contract. What breaks in a HashMap if a class...": https://scrivio-interview-library.netlify.app/java/object-contracts/d6e87caa83/

More in Object methods and contracts