Video in progress
What happens in a HashMap if a class overrides equals but you forget hashCode?
Equal objects get different hashes and land in different buckets. As a result, get with a freshly created "equal" key returns null, and a HashSet ends up with duplicates.
📖 Answer
The contract is simple: if a.equals(b), then a.hashCode() == b.hashCode() must hold. The reverse is not required, since different objects can have colliding hashes.
class Passport {
final String series;
Passport(String s) { series = s; }
@Override public boolean equals(Object o) {
return o instanceof Passport p && p.series.equals(series);
}
// no hashCode, so Object's version is used
}
Map<Passport, String> owners = new HashMap<>();
owners.put(new Passport("AA1234567"), "Ali");
owners.get(new Passport("AA1234567")); // almost always null
HashMap never even gets to equals: it picks a bucket by hash first, and it turns out to be a different bucket.
A bug like this often stays hidden in tests, because the test works with a single object reference. On prod the key is rebuilt from a DTO and the cache stops working.
The fix: write both together, with IDE generation, Objects.hash(...), or, easiest of all, a record.
Sign up to mark studied questions and save your progress.