ProgrammingHardGATE CS · TCS NQT Prime · Product Company SDE

A class overrides equals() but does not override hashCode(). What bug does this risk for instances used as keys in a HashMap or stored in a HashSet?

  1. A. The code fails to compile, since overriding equals() without hashCode() is illegal
  2. B. This causes no bug at all, since hashCode() has no effect on HashMap behaviour
  3. C. Two objects considered 'equal' by equals() can still land in different hash buckets, since the inherited Object.hashCode() is identity-based, so the map/set may wrongly treat them as distinct entries
  4. D. hashCode() is automatically derived from the equals() logic by the compiler

Correct answer: C. Two objects considered 'equal' by equals() can still land in different hash buckets, since the inherited Object.hashCode() is identity-based, so the map/set may wrongly treat them as distinct entries

HashMap/HashSet first compare hash codes to find a candidate bucket and only then call equals(); if hashCode() is not overridden consistently with equals(), equal objects may end up in different buckets and never be found as duplicates.

More OOP with C++ and Java questions

Exams that ask this topic