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.
Saved automatically
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.
Related Questions in Java
Advanced Java Interview Questions and Answers
Advanced level • 845 views
Java Web development interview questions
Advanced level • 666 views
Java Interview questions
Advanced level • 633 views
Java questions for Newbies
Intermediate level • 579 views
Interview questions on EJB
Advanced level • 458 views