【发布时间】:2013-05-19 16:55:37
【问题描述】:
字符串字面量的行为在下面的代码中非常令人困惑。
我可以理解第1行、第2行和第3行是true,但为什么第4行是false?
当我打印两者的哈希码时,它们是相同的。
class Hello
{
public static void main(String[] args)
{
String hello = "Hello", lo = "lo";
System.out.print((Other1.hello == hello) + " "); //line 1
System.out.print((Other1.hello == "Hello") + " "); //line 2
System.out.print((hello == ("Hel"+"lo")) + " "); //line 3
System.out.print((hello == ("Hel"+lo)) + " "); //line 4
System.out.println(hello == ("Hel"+lo).intern()); //line 5
System.out.println(("Hel"+lo).hashCode()); //hashcode is 69609650 (machine depedent)
System.out.println("Hello".hashCode()); //hashcode is same WHY ??.
}
}
class Other1 { static String hello = "Hello"; }
我知道== 检查引用相等性并在池中检查文字。我知道equals() 是正确的方法。我想了解这个概念。
这个question我已经查过了,但是没有解释清楚。
希望得到完整的解释。
【问题讨论】:
-
+1 好奇.. 第一个问题很好
-
因为哈希码相等并不意味着对象身份。请参阅
Object.hashCode().的 Javadoc -
如果你知道这一点,你就不会引发共振级联场景!
标签: java string string-interning