本文共 747 字,大约阅读时间需要 2 分钟。
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,但它没有解释清楚。
我会感谢一个完整的解释。
转载地址:https://blog.csdn.net/weixin_32256355/article/details/115089522 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!