← Java roadmap

Topic 20 of 30 · Beginner

Why must equal HashMap keys have the same hash code?

HashMap uses a hash to select candidate storage and equals to find an equivalent key. Equal objects must have equal hashes, although unequal objects may collide.

BasicEntry level · 0–1 yearsCollections

Java 17+; compile each complete program as Main.java.

Detailed answer

HashMap uses a hash to select candidate storage and equals to find an equivalent key. Equal objects must have equal hashes, although unequal objects may collide.

Override equals and hashCode together. Mutating a field used by either after insertion can leave the key stored under its old hash and make lookups fail.

Use immutable keys such as records with immutable components; record equality does not deep-copy mutable components or make their contents immutable.

Internal working

HashMap spreads hashes, selects a bucket and compares keys. Collision handling is an implementation concern; identity-based default equals is often wrong for value keys.

Practical scenario

Two customer IDs with equal content are constructed separately. A custom key overrides equals only and the second lookup misses.

import java.util.*;
class Main {record Key(int id){} public static void main(String[] a){var m=new HashMap<Key,String>();m.put(new Key(1),"Ada");System.out.println(m.get(new Key(1)));}}
Common mistakes
  • Overriding equals but not hashCode.
  • Mutating key fields after insertion.
Key takeaways
  • Equal keys require equal hashes.
  • Keep keys stable.
  • Prefer immutable value objects.
Follow-up challenges
  • Why can two unequal keys share a hash?
  • Are records deeply immutable?
Practise Java with the AI mentor

Can't find a Java topic you need for exams or placements? Request it and we'll add it.