user1878962
user1878962

Reputation: 21

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?

Upvotes: 2

Views: 360

Answers (3)

Joachim Sauer
Joachim Sauer

Reputation: 308031

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).

Upvotes: 7

dicheridoo
dicheridoo

Reputation: 89

someone correct me if i'm wrong, but i think yes, it is the correct output as you get the hascode for the string "hi" and not for the string-objects. and that's exactly what the hashcode-method should do.

Upvotes: 1

assylias
assylias

Reputation: 328608

All your strings are equal so it makes sense that they have the same hashcode. That is part of the contract for hashcode defined in Object:

If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Upvotes: 3

Related Questions