Java: Which practice avoids a common mistake with equals() and hashCode() Contract?

Difficulty:

Medium

Questions:

1

Time Limit:

2 minutes

Passing Score:

100%

Question

Which practice avoids a common mistake with equals() and hashCode() Contract?

  1. Ignore the equals() and hashCode() Contract issue and rely on team discipline instead of APIs or contracts.
  2. Silence the equals() and hashCode() Contract problem by using raw types, broad catches, or shared mutable state.
  3. Prefer the version of equals() and hashCode() Contract that makes behavior less predictable as long as the code compiles.
  4. Do not base hashCode on mutable state that can change after the object enters a hash-based collection.

Hint

Look for the option that protects correctness instead of hiding the problem.

Answer and rationale

Correct answer: D. Do not base hashCode on mutable state that can change after the object enters a hash-based collection.

Do not base hashCode on mutable state that can change after the object enters a hash-based collection. This is a common failure mode in real Java code and a frequent interview follow-up.

Track: Java