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?
- A. The code fails to compile, since overriding equals() without hashCode() is illegal
- B. This causes no bug at all, since hashCode() has no effect on HashMap behaviour
- 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
- 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
- Which run-time mechanism lets a call through a base-class pointer invoke the correct derived-class override in C++?
- cpp struct A { void f() { cout << "A::f"; } }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; d.f(); } What…
- Why can a private method in a Java superclass never be overridden by a subclass, only unintentionally hidden (i.e. always statically bound)?
- cpp struct A { int x = 1; }; struct B : A {}; struct C : A {}; struct D : B, C {}; int main() { D d; // d.x ? } Without virtual…
- Why did Java and C# choose single inheritance of classes plus multiple inheritance of interfaces, instead of C++-style full multiple…
- Which statement correctly distinguishes an abstract class from an interface in Java (interfaces may have default/static/private methods…