Difficulty: Easy
Correct Answer: 2 and 3
Explanation:
Introduction / Context:
This question checks common misconceptions about hashCode()
. Knowing what the method guarantees—and what it does not—is essential for using hash-based collections correctly.
Given Data / Assumptions:
Concept / Approach:
The contract requires that equal objects have equal hash codes but places no positivity requirement on the integer returned. Many classes, such as String
, override hashCode()
. Two identical values for String
(e.g., the empty string) will indeed produce the same hash code, as defined by its algorithm.
Step-by-Step Solution:
String
instances with the same content (e.g., "") have equal hash codes (for empty string, the result is 0).
Verification / Alternative check:
JDK source shows String.hashCode()
computes a polynomial hash; for empty content, the accumulation yields 0.
Why Other Options Are Wrong:
Common Pitfalls:
Believing hash codes must be non-negative, or that String
inherits Object’s default implementation.
Final Answer:
2 and 3
Discussion & Comments