Verified Jobs Live
Java Medium Level ~3 min read

Why must equals and hashCode agree for keys stored in HashMap?

Interactive Practice Mode
Formulate your thoughts or take notes before revealing the model solution.
Model Answer & Deep-Dive Explanation

HashMap uses a key’s hash code to locate a bucket and equality to identify the matching key. If two equal objects produce different hash codes, lookup may search the wrong bucket. Equal objects must therefore have equal hash codes; unequal objects may legitimately collide. Do not mutate fields used by equals or hashCode while the object is a map key, because the entry remains in the bucket chosen at insertion. Test reflexivity, symmetry, transitivity, null handling, and retrieval with a separately constructed equivalent key.