String s1="abc";
String s2=new String("abc");
when we compare the both
s1==s2; it return false
and when we compare it with s1.hashCode()==s2.hashCode it return true
i know (==) checks reference id's .Does it returning true in above comparison because above hashCode are saved to same bucket??Please give me explanation
Don't forget that your hash codes are primitive integers, and comparing primitives using
==
will compare their values, not their references (since primitives don't have references)Hence two strings having the same contents will yield the same hash code, and a comparison via
==
is perfectly valid.The concept of a bucket is only valid when you put an object into a hashed collection (e.g. a
HashSet
). The value of the hash code dictates which bucket the object goes into. The hash codes themselves aren't stored.