Difficulty: Easy
Correct Answer: 1 and 4
Explanation:
Introduction / Context:
The equals–hashCode contract in Java defines how logical equality relates to hash codes, especially for use in hash-based collections. This item tests which implications are valid and which are not.
Given Data / Assumptions:
equals()
and hashCode()
are correctly overridden for the class.
Concept / Approach:
The key rules: If a.equals(b)
is true, then a.hashCode() == b.hashCode()
must be true. However, the converse is not guaranteed: identical hash codes do not imply equality, because many objects can map to the same hash bucket. If a.equals(b)
is false, there is no requirement on the relation of their hash codes; they may collide or differ.
Step-by-Step Solution:
Verification / Alternative check:
Consider two different String
values that happen to collide under a custom hash; their hash codes could match but equals()
would still return false.
Why Other Options Are Wrong:
Common Pitfalls:
Assuming equal hash codes imply object equality; hash codes only partition objects, they do not define identity.
Final Answer:
1 and 4
Discussion & Comments