Scrivio Interview library
DebuggingFoundations7 min read · updated 12 November 2026

A class overrides equals but not hashCode. Explain what goes wrong when instances are used as HashMap keys, and how to implement both correctly.

The contract says that equal objects must have equal hash codes, but Object.hashCode() is based on identity, so two equal instances almost always get different hash codes. HashMap uses the hash code to choose a bucket, so map.get(equalKey) looks in the wrong bucket and returns null even though an equal key is in the map. We fix it by computing hashCode from exactly the fields used in equals, for example with Objects.hash(a, b), by keeping those fields immutable, or simply by using a record, which generates both consistently.

Why this question is asked

This bug is easy to write and hard to see, because nothing fails loudly. The map just behaves as if our keys were not there: lookups return null, contains() returns false, and a HashSet happily stores duplicates. It shows up as a cache that never hits or a deduplication step that does not deduplicate. Interviewers ask it because the answer requires understanding how hash-based collections find keys. In this answer, we will recap the contract between equals and hashCode, reproduce the failure, walk through why get() misses, implement both methods correctly, look at the separate danger of mutable keys, and see how records make the problem go away.

1A Quick Recap of the equals and hashCode Contract

equals() decides whether two objects represent the same value. hashCode() turns an object into an int that hash-based collections such as HashMap and HashSet use to decide where to store it. The two are linked by a rule in the Object documentation: if a.equals(b) is true, then a.hashCode() must equal b.hashCode(). The reverse is not required; unequal objects may share a hash code, which is just a collision.

If we do not override hashCode(), we inherit Object.hashCode(), which is based on the object's identity. In practice it is effectively random per object, so two separately created objects get different values even when our equals() says they are equal. That breaks the rule.

2Reproducing the Problem

Here is a key class that overrides equals but forgets hashCode.

Java
final class CustomerId {
private final String region; private final long number;
CustomerId(String region, long number) { this.region = region; this.number = number; }
@Override public boolean equals(Object o) {
return o instanceof CustomerId other && other.region.equals(region) && other.number == number;
}
// hashCode() not overridden
}
Map<CustomerId, String> names = new HashMap<>();
names.put(new CustomerId("EU", 42), "Asha");
new CustomerId("EU", 42).equals(new CustomerId("EU", 42)); // true
names.get(new CustomerId("EU", 42)); // null (almost always)
names.containsKey(new CustomerId("EU", 42)); // false
Set<CustomerId> ids = new HashSet<>();
ids.add(new CustomerId("EU", 42)); ids.add(new CustomerId("EU", 42));
ids.size(); // 2, a duplicate

Notice the word 'almost'. Very rarely, two separately created objects happen to get exactly the same identity hash code, and then the lookup works, because HashMap reaches equals(). That makes the bug look intermittent, which is worse than a consistent failure.

3Why get() Looks in the Wrong Bucket

HashMap stores entries in an array of buckets. To find a key, it computes the key's hash code, picks a bucket from it, and only then compares the keys inside that bucket, checking the stored hash first and calling equals() only when the hashes match.

So the lookup key, a brand-new CustomerId, has its own identity hash code, which points to a different bucket than the one where the first CustomerId was stored. HashMap searches that other bucket, finds nothing equal there, and returns null. Our carefully written equals() is never even called. Even if both happened to land in the same bucket, the stored hash would differ, so HashMap would still skip the entry before calling equals().

Step throughWhat names.get(new CustomerId("EU", 42)) does
  1. Call hashCode() on the lookup keyidentity-based: a new, unrelated number
  2. Pick a bucket from the hasha different bucket from where the stored key sits
  3. Any entry in that bucket with the same hash?
    YesCall equals() to confirmNoReturn null

3 steps in order. Play them, or step through them one at a time.

Without a matching hashCode, HashMap never reaches equals(), so equal keys are invisible.

4Implementing Both Correctly

The fix is to compute hashCode() from exactly the same fields that equals() compares. Then equal objects necessarily produce equal hash codes.

Java
final class CustomerId {
private final String region; private final long number;
CustomerId(String region, long number) { this.region = Objects.requireNonNull(region); this.number = number; }
@Override public boolean equals(Object o) {
if (this == o) return true;
return o instanceof CustomerId other && region.equals(other.region) && number == other.number;
}
@Override public int hashCode() {
return Objects.hash(region, number); // same fields as equals
}
}
names.put(new CustomerId("EU", 42), "Asha");
names.get(new CustomerId("EU", 42)); // Asha

Objects.hash() is convenient and correct; it boxes its arguments into an array, which costs a little in very hot code, where 31 * region.hashCode() + Long.hashCode(number) does the same without allocation. Two other details matter. The class is final, which keeps the instanceof-based equals symmetric, since a subclass cannot add fields that break it. And we must never include a field in hashCode() that equals() ignores, or equal objects could again get different hashes.

5Keep Key Fields Immutable

There is a second, related failure. If a field used in hashCode() changes while the object is a key in a map, the entry stays in the bucket chosen by the old hash, and lookups now compute the new hash and search elsewhere.

Java
class MutableKey { String code; MutableKey(String c) { code = c; }
public boolean equals(Object o) { return o instanceof MutableKey k && k.code.equals(code); }
public int hashCode() { return code.hashCode(); } }
MutableKey k = new MutableKey("A");
Map<MutableKey, Integer> m = new HashMap<>();
m.put(k, 1);
k.code = "B"; // the hash changes while the key is inside the map
m.get(k); // null: searched in B's bucket
m.get(new MutableKey("A")); // null: right bucket, but equals now fails
m.size(); // 1, an entry nobody can reach

The entry is effectively lost, and it also leaks memory. So key fields should be final, as in our corrected CustomerId. This is also a good reason never to use a JPA entity with a generated id as a HashSet element before it is saved, because its id changes from null to a value on persist.

6Records Do It for Us

For value-like keys, the simplest solution is a record. Java generates equals(), hashCode() and toString() from the components, consistently, and the components are final.

Java
record CustomerId(String region, long number) {}
Map<CustomerId, String> names = new HashMap<>();
names.put(new CustomerId("EU", 42), "Asha");
names.get(new CustomerId("EU", 42)); // Asha
new CustomerId("EU", 42).hashCode() == new CustomerId("EU", 42).hashCode(); // true

A record's fields are shallowly immutable: if a component is a mutable List, the list itself can still change, so key components should be immutable types too. With that caveat, records remove this whole class of bug for keys and value objects.

7Follow-up questions

Is it a problem to override hashCode but not equals?

Yes, in the opposite way. Equal-looking objects would land in the same bucket, but the inherited equals() compares identity, so HashMap would still treat them as different keys. The two methods must always be overridden together and based on the same fields.

Does a bad hashCode, such as always returning 1, break correctness?

No, it only breaks performance. Every key lands in one bucket, so lookups compare against many entries. Since Java 8, a crowded bucket turns into a tree, which helps if keys are Comparable, but it is still far slower than a good spread. Correctness only requires that equal objects have equal hashes.

How do you test equals and hashCode?

Write a test that two equal instances are equal and have the same hash, that unequal ones are not equal, and that equals is reflexive, symmetric and handles null. Libraries such as EqualsVerifier check the whole contract, including subclass and mutability issues, in one line.

8Conclusion

In this answer, we saw that overriding equals without hashCode breaks the rule that equal objects must have equal hash codes. HashMap picks a bucket from the identity-based hash, so lookups with an equal key search the wrong bucket and return null, and sets keep duplicates. We fixed it by deriving hashCode from the same fields as equals with Objects.hash, kept key fields final so hashes never change inside a map, and saw that records generate both methods correctly.

What to say in the interviewAbout 80 seconds aloud

Open with

The rule is that if two objects are equal, they must have the same hash code. If a class overrides equals but not hashCode, it inherits Object's identity-based hashCode, so two equal instances almost always get different numbers.

Then, if they want more

HashMap uses the hash code to pick the bucket before it ever calls equals. So when I put new CustomerId("EU", 42) and later call get with another new CustomerId("EU", 42), the lookup goes to a different bucket, finds nothing, and returns null, even though an equal key is in the map.

The same thing makes containsKey false and lets a HashSet hold duplicates. It can even work occasionally by chance, which makes it look intermittent. To fix it, I compute hashCode from exactly the fields used in equals, for example Objects.hash(region, number), and never include fields that equals ignores.

I make the class final so equals stays symmetric, and I make the key fields final, because if a field in the hash changes while the object is in the map, the entry stays in the old bucket and becomes unreachable.

For value objects like this, the simplest answer is a record, which generates consistent equals, hashCode and toString from its components. I would also add a test, or use EqualsVerifier, to check the contract.

About this answer

Last updated
12 November 2026
Versions it names
Java 8
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. 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 "A class overrides equals but not hashCode. Explain what goes wrong when instances are...": https://scrivio-interview-library.netlify.app/java/clean-code/eea32bc99e/