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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With