Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

two string instances seems same, but their hashcode are different

    String a = "success";
    String b = "success";

    System.out.println(a.hashCode());
    System.out.println(b.hashCode());

    if(a.equals(b)){
        System.out.println("123");
    }

I can't understand why the two string have different hashcode.

    String a = "success";
    String b = "success";

    System.out.println(a.hashCode());
    System.out.println(b.hashCode());

    System.out.println(System.identityHashCode(a));
    System.out.println(System.identityHashCode(b));

output:

-1867169789
1954952228
33263331
6413875
like image 975
Dean White Avatar asked Aug 19 '26 11:08

Dean White


1 Answers

You've inserted the zero width no-break space (U+FEFF) character at the beginning of your second string.

That string is actually equal to the following string (no hidden unicode characters): "\ufeffsuccess"

That means a and b are not equal and do not have the same hash code.

like image 166
fabian Avatar answered Aug 22 '26 01:08

fabian