• Post Reply Bookmark Topic Watch Topic
  • New Topic

hashCode() in String  RSS feed

 
Deepak Sahu
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

Can someone give the clarrification of the following question ?

String s1="abc";
String s2=new String("abc");
I found that s1.hashCode()=s2.hashCode() although both are different objects ?Can someone explain me why s1.hashCode()=s2.hashCode() ?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16057
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hash codes are not necessarily different for different objects. Also, both of your String objects are equal, so they must have the same hash code. The hash code is not a unique identifier of an object.

Note what the documentation of Object.hashCode says:

  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!