0

In Java I did this :

    String s1=new String("USA");
    String s2 = new String("Canada");
    String s3=new String("Canada");
    String s4 = new String("Canada");
    String s5=new String("Canada");

    System.out.println(s1.hashCode());      
    System.out.println(s2.hashCode()); 
    System.out.println(s3.hashCode());
    System.out.println(s4.hashCode()); 
    System.out.println(s5.hashCode());

  Output :
  3254818
  96801
  96801
  96801
  96801

My questions :

  1. Even though, the hashcode of s2, s3, s4 and s5 are same, is it ok to say that they are different String objects. Since, we are using new () to create s2-s5 objects, is it correct to say that s2, s3, s4 and s5 are distinct objects and they do not share their string value (Canada) in String pool ?

  2. The hashcode values of s2-s5 are same. Is it a pure co-incidence ?

Please explain.

Navchetan
  • 153
  • 1
  • 2
  • 11
  • https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html see the documenation of hascode for detail. – jilen Nov 23 '14 at 02:49

1 Answers1

0

That's normal. A hash is an algorithm based on an input always having the same output. It is by no means a random generator. If you want them to be different, the string values should be unique. You can also add a value like an ID to the hash, so that s2 would be Canada, but when you hash it, you hash Canada-s2. that's a unique string, so you would get a unique output.

DAB
  • 1,303
  • 14
  • 23
  • So, is it correct : s2, s3, s4 and s5 are all different objects with their own value :"Canada" stored in different locations on heap ? – Navchetan Nov 23 '14 at 02:47
  • yes, a better test might be to change the value of s2, then check the value of s3 and you will see that they are different. – DAB Nov 23 '14 at 02:48