kamal kamal - 3 months ago 16
Java Question

Why hash code is same for String s1= "cat" and String s2= new String("cat")?

Program :

class JavaCode
{
public static void main (String[] args) throws java.lang.Exception
{
String s1 ="cat";
String s2 = new String("cat");
System.out.println(s1 == s2);
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
}
}


Output :

false
98262
98262


If S1 and S2 are pointing to different memory address, then Hash code should be different for them? Please Explain how they are same?

Kon Kon
Answer

If S1 and S2 are pointing to different memory address, then Hash code should be different for them?

No, this is not how hash codes work. If two objects are equal, their hash code MUST be equal too. It doesn't matter "where in memory" they sit.

I recommend reading through the following article: http://www.javaworld.com/article/2074996/hashcode-and-equals-method-in-java-object---a-pragmatic-concept.html