Which statements about the hashCode() method are incorrect for Java types?

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:

  • Statements considered: (1) Collections use hash codes to locate objects; (2) hashCode must be positive; (3) String uses Object’s hashCode; (4) Two new empty Strings have identical hash codes.


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:

(1) True: Hash-based collections (HashMap, HashSet) use hash codes to bucket elements.(2) False: hashCode() may be negative; there is no positivity requirement.(3) False: String overrides Object.hashCode() with its own computation.(4) True: Two new 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:

  • Any pair including (1) or (4) as incorrect contradicts standard library behavior.


Common Pitfalls:
Believing hash codes must be non-negative, or that String inherits Object’s default implementation.


Final Answer:
2 and 3

Discussion & Comments

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