以下代码中,字符串字面值的行为非常令人困惑。
我可以理解第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()
是正确的方法。 我想了解这个概念。
我已经查看了这个问题,但它没有清楚地解释。
我将非常感谢一份完整的解释。
Object.hashCode()
的Javadoc。 - user207421