-4

Consider the piece of code given below. I was wondering how can a string present in string pool "s1" or "s2" have the same hashCode as a string present in heap as "s3" but outside string pool.

class Test{
public static void main(String[] args) {
    String st1 = "Shiva";
    String st2 = "Shiva";
    String st3 = new String("Shiva");
    System.out.println(st1 == st2);
    System.out.println(st1 == st3);
    System.out.println(st2 == st3);
    System.out.println(st1.hashCode());
    System.out.println(st2.hashCode()); 
    System.out.println(st3.hashCode());
    }
}

input: deep (master *) LanguagePackageInJava $ javac Lecture3.java
output: deep (master *) LanguagePackageInJava $ java Test
true
false
false
79855167
79855167
79855167

I have searched a lot regarding this question. Please do tell me where am I wrong in my thought process.

trincot
  • 317,000
  • 35
  • 244
  • 286

1 Answers1

-1

hashcode and equals method have contract , so if two string are true for equals then their hashcode should be same.

Sandeep Chauhan
  • 141
  • 1
  • 2
  • 8
  • but hashCode is depending upon address, so how can it be possible that one present in string pool and the other present in heap outside the string pool have a same hashCode – Grounded Snippets Aug 05 '18 at 18:35
  • 2
    String hashcode generation is not dependent on address location of variable. As per java doc String.hashcode() `Returns a hash code for this string. The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)` – Sandeep Chauhan Aug 05 '18 at 18:37
  • The hash code never depends on the address - that is on old myth. The hash code of an object must never change, but the garbage collector moves objects around, meaning that the address of objects change almost randomly – Thomas Kläger Aug 05 '18 at 19:54