String文字的行为在下面的代码中是非常混乱的。
我可以理解行1,行2和行3是真的,但为什么是行4假?
当我打印它们的哈希码时,它们是相同的。
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,但它没有解释清楚。
我会感谢一个完整的解释。