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:
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:
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:
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