This question already has answers here:
How do I compare strings in Java?
(23个答案)
What is the difference between “text” and new String(“text”)?
(11个答案)
3个月前关闭。
但是当我使用时:
有人可以在这里解释区别吗?谢谢!
在第二个示例中,通过
我创建了前一阵子,重点介绍了一些显示这种行为的情况。
您可以使用
(23个答案)
What is the difference between “text” and new String(“text”)?
(11个答案)
3个月前关闭。
public class Test {
public static void main(String[] args)
{
String s1 = "HELLO";
String s2 = "HELLO";
System.out.println(s1 == s2); // true
}
}
但是当我使用时:
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); // false
}
}
有人可以在这里解释区别吗?谢谢!
最佳答案
在第一个例子中
String s1 = "HELLO";
String s2 = "HELLO";
s1
和s2
的值是编译时常量。因此,编译器仅生成单个String
对象,并保存值"HELLO"
并将其赋给s1
和s2
。这是Common Subexpression Elimination(一种著名的编译器优化)的特例。因此s1 == s2
返回true
。在第二个示例中,通过
String
显式构造了两个不同的new
。因此,根据new
的语义,它们必须是单独的对象。我创建了前一阵子,重点介绍了一些显示这种行为的情况。
您可以使用
String
强制返回相同的String::intern()
:String s1 = new String("HELLO").intern();
String s2 = new String("HELLO").intern();
System.out.println(s1 == s2); // will print "true";