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