A class that overrides equals but leaves the default identity-based hashCode places equal objects in different hash buckets, so a HashSet or HashMap fails to recognize an equal object as already present.
class BadKey {
final int id;
BadKey(int id) { this.id = id; }
@Override
public boolean equals(Object o) {
return o instanceof BadKey k && k.id == id;
}
}
Set<BadKey> set = new HashSet<>();
set.add(new BadKey(1));
System.out.println("Contains equal key: " + set.contains(new BadKey(1)));
System.out.println("Set size: " + set.size());
Contains equal key: false
Set size: 1
Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.
Published 2026-09-27