Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

testing hashCode for Strings

I am writing the code shown below:

String s1=new String("hi");
System.out.println(s1.hashCode());
String s2=new String("hi");
System.out.println(s2.hashCode());
String s3=s1.intern();
String s4=s2.intern();
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());

When I run the code the same hashcode is printing for all variables:

3329
3329
3329
3329

Is it correct output for the above code?

like image 493
user1878962 Avatar asked Jan 22 '26 11:01

user1878962


1 Answers

Yes, that's the correct output. The hashCode of String is based on the content of the String (in a very specific way, documented in the documentation linked to above).

And since s1, s2, s3 and s4 all have the same content ("hi"), they all return the same hashCode.

That's actually required since object to which a.equals(b) return true are required to return the same values for a.hashCode() and b.hashCode().

Note that the opposite (i.e. "objects with the same hashcode have to be equal") is not true and can't even be done in general (simply consider that there are a lot more possible String values than there are int values, see the pigeonhole principle).

like image 190
Joachim Sauer Avatar answered Jan 25 '26 01:01

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!