Core Java: Overriding equals without hashCode breaks HashMap and HashSet lookups

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.

Code
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());
Output
Contains equal key: false
Set size: 1
Advertisement
More in JAVA

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

© Java Coding Hub · About · Contact · Privacy · Terms