Small question.
String s1 = "test";
String s2 = "test";
s1,s2 both have same hashCode value
String sn1 = new String("java");
String sn2 = new String("java");
all of them said sn1 and sn2 have different hashCode values and those are different objects
When I am printing hashCode values it gives same value that means sn1 and sn2 points to the same object or not ?
Hash codes should be equal if objects are equal (the reverse is not true , however). Since
sn1.equals(sn2) // true
We can conclude that
sn1.hashCode() == sn2.hashCode() // true
It is often useful to look at the java code to see what is happening.
For example the String#hashCode
method
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
As you can see the result is based upon the value of the String, not its memory location.
If you are comparing Strings like:
s1 == s2
then you're comparing the pointer (the reference) of the String
. This reference is not what you're getting from the String#hashCode method.
If you are comparing Strings like:
s1.equals(s2)
then the method String#equals uses the String#hashCode methods of both Strings
and compares the results.
Try it out by yourself:
public class StringEquality {
public static void main(String[] args) {
String s1 = new String("java");
String s2 = new String("java");
// hashCodes
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
// equality of hashCodes
System.out.println(s1.equals(s2));
// references
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
// equality of references
System.out.println(s1 == s2);
}
}
Will print something like:
3254818
3254818
true
1072624107
1615633431
false
All of who? sn1
and sn2
are different objects, but they are identical, so they have the same hash code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.