Skip to content
Sharp

Core Java · interview question

A developer wishes to use a custom object as a key in a HashMap. What must be carefully considered to prevent bugs?

Multiple choiceHardchapter-4-curatedpremiumcore-javaequals-and-hashcode-in-collections
Choose one answer
Answer and explanation

Correct answer

B. Both equals and hashCode methods must be correctly implemented.

Why

To use a custom object as a key in a HashMap, the equals and hashCode methods must be implemented correctly and consistently. This ensures that keys can be reliably located and retrieved, preventing subtle bugs that occur when the map cannot find entries due to hash collisions or equality mismatches.

Test yourself on Core Java

A free test with instant, explained results. No account needed.

Start free test
All Core Java questions →