[英]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
You've inserted the zero width no-break space (U+FEFF) character at the beginning of your second string. 您已在第二个字符串的开头插入了零宽度的不间断空格(U + FEFF)字符。
That string is actually equal to the following string (no hidden unicode characters): "\success"
该字符串实际上等于以下字符串(无隐藏的unicode字符): "\success"
That means a
and b
are not equal and do not have the same hash code. 这意味着a
和b
不相等,并且没有相同的哈希码。
public class Compare {
public static void main(String args[]) {
String a = "success";
String b = "success";
char[] aChar = a.toCharArray();
char[] bChar = b.toCharArray();
for(int i = 0; i < aChar.length; i++)
{
System.out.println((int)aChar[i]);
}
System.out.println("");
for(int i = 0; i < bChar.length; i++)
{
System.out.println((int)bChar[i]);
}
}
}
The first char of the second string is char 65279. Did you copy the strings from somewhere? 第二个字符串的第一个字符是char65279。您是否从某个地方复制了字符串?
The Strings look the same, but are not. 字符串看起来相同,但不同。 Try typing the "success" text again, then it should work. 尝试再次输入“成功”文本,那么它应该起作用。
当我将代码复制并粘贴到IDE中时,它表明b =的开头双引号“成功实际上是一个奇怪的双引号,而不是标准的双引号。Bizzarrely,我得到了与您相同的结果-代码编译并运行,但输出不同的哈希码。通过将双引号固定为普通的双引号,哈希码现在相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.