2

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?

2
  • 2
    Is there a reason to doubt the output of the JVM? What did you expect?. Commented Dec 5, 2012 at 12:22
  • You might also try "iJ".hashCode() to confirm that different strings can also produce that same hash. Commented Dec 5, 2012 at 12:33

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.