Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashcode

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?

like image 708
kamal Avatar asked Jul 09 '26 23:07

kamal


1 Answers

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

like image 91
Kon Avatar answered Jul 11 '26 13:07

Kon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!