public class Main {
public static void main(String[] args) {
String str1="shrey";
String str2="shrey";
String str3=new String("shrey");
System.out.println(str1.hashCode());
System.out.println(str2.hashCode());
System.out.println(str3.hashCode());
}
}
output = same hashcode of all str1, str2, str3
Java uses string pool. I know it. str1 and str2 are created using string literal so they should refer to same object and hence will generate the same hashcode but, str3 is created using new keyword, so I was expecting hashcode of str3 to be different but it came out to be same. Why?
Your question is based on false assumptions:
Correct
Incorrect! Nothing in any of the Java specifications states that hashcodes are unique. In fact, the closest it comes to that is this line from the javadocs for
Object.That says try to make them distinct if you can ... but it does not guarantee that they will be distinct. Indeed, it is provably impossible to guarantee that in the context of Java.
That is nothing to do with
Object::hashCode. You code is actually calling theString::hashCode, and that is specified to return a value that is independent of the string's identity. TheStringjavadoc states:Your strings all have the same length and the same characters, so that means that
String::hashCodewill give the same result.We can also infer that this should be the case from the properties of
hashCodeandequalsas set out in theObjectjavadocs. In concise terms: