Hashcode of String new () objects showing same values

58 views Asked by At

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.

1

There are 1 answers

2
DAB On

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.