Choosing the correct facts about properly overridden hashCode() and equals(): which two statements are valid in Java?

Difficulty: Medium

Correct Answer: equals() need not be overridden if hashCode() is, and hashCode() may legally return the same value for all instances.

Explanation:


Introduction / Context:
This item probes nuances of the equals–hashCode contract. Overriding equals() usually implies you should also override hashCode() to preserve the contract for hash-based collections. The converse, however, is not required by the language specification. It also asks about the permissibility (though not desirability) of constant hash codes.


Given Data / Assumptions:

  • “Properly overridden” means implementations obey reflexive, symmetric, transitive, consistent properties for equals(), and hashCode() consistency with equals().
  • We judge truth of the provided statements against that contract.


Concept / Approach:
Rule of thumb: If you override equals(), you must override hashCode() so that equal objects have equal hash codes. However, you can override hashCode() alone (e.g., for performance or distribution), leaving equals() as identity. Also, the specification allows hashCode() to return a constant; it still satisfies the contract but causes poor performance due to excess collisions.


Step-by-Step Solution:

Statement 1 (“hashCode does not have to be overridden if equals is”): Misleading → to be proper, you should override both; otherwise equal objects could produce different hash codes, breaking collections.Statement 2 (“equals need not be overridden if hashCode is”): True; the default identity equals remains valid with any hashCode that is consistent (e.g., also identity-based or constant).Statement 3 (“hashCode can always return the same value”): True; contract permits it, but performance suffers.Statement 4 (“equals can be true for different objects”): True in general, but the question asks for two statements; the conventional exam pairing emphasizes 2 and 3 as the essential contract facts.


Verification / Alternative check:
The JDK docs for Object.equals and Object.hashCode describe these relationships and warn about broken contracts in hash-based collections when equals() is changed without hashCode().


Why Other Options Are Wrong:

  • Options including statement 1 promote a broken contract if equals() is customized but hashCode() is not.
  • Options excluding statement 3 miss a permissible (though poor) implementation allowed by the spec.


Common Pitfalls:
Confusing “legal” with “performant”; constant hash codes are legal but disastrous for HashMap/HashSet load distribution. Also, thinking overriding hashCode() forces overriding equals(); it does not.


Final Answer:
equals() need not be overridden if hashCode() is, and hashCode() may legally return the same value for all instances.

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion