Java Programming - Objects and Collections - Discussion

3. 

Which of the following statements about the hashcode() method are incorrect?

  1. The value returned by hashcode() is used in some collection classes to help locate objects.
  2. The hashcode() method is required to return a positive int value.
  3. The hashcode() method in the String class is the one inherited from Object.
  4. Two new empty String objects will produce identical hashcodes.

[A]. 1 and 2
[B]. 2 and 3
[C]. 3 and 4
[D]. 1 and 4

Answer: Option B

Explanation:

(2) is an incorrect statement because there is no such requirement.

(3) is an incorrect statement and therefore a correct answer because the hashcode for a string is computed from the characters in the string.


Jjj said: (Sep 14, 2015)  
Two new empty String objects will produce identical hash codes.

The above will produce unique hash codes right and therefore its incorrect or am I wrong?

Radistao said: (Dec 5, 2015)  
Damn, guys, hashCode(), not hashcode() - JAVA METHODS ARE CASE SENSITIVE!

Ford Prefect said: (Jul 18, 2016)  
The question is asked in a confusing way. The text should be changed from "incorrect" to "correct" and the answer should be inverted. Also, it's hashCode () not hashcode ().

Hepbo3Ah said: (Jul 20, 2016)  
@Jjj you are correct.

Two empty strings do produce identical hashCode(). Also, some Collections DO use hashCode() to store help locate the data, namely HashMap. Its even has a "hash" in its name. Terrible question

Avinash said: (Oct 5, 2016)  
Every object uses hashCode, why only for some collections?

Sat said: (Dec 15, 2016)  
The hashCode always return positive int value, not a negative value, or float or double etc then how the #2 is wrong?
As #3 as for giving string class inherit hashCode() from object class that is correct because it is mentioned to inheritance not for how the hashCode is calculated for a string?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.