Java equality vs hashing: For two instances of the same class with properly overridden equals() and hashCode(), which statements are logically correct?

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:

  • Both equals() and hashCode() are correctly overridden for the class.
  • We compare two instances of the same 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:

Statement 1: If equals() returns true, hashCode() == must be true → Correct.Statement 2: If equals() returns false, hashCode() != must be true → Incorrect (collisions allowed).Statement 3: If hashCode() == is true, equals() must return true → Incorrect (collisions allowed).Statement 4: If hashCode() == is true, equals() might return true → Correct (it may or may not).


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:

  • Any choice implying 2 or 3 is correct contradicts the contract.


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

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