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个月前关闭。
            
        

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";


s1s2的值是编译时常量。因此,编译器仅生成单个String对象,并保存值"HELLO"并将其赋给s1s2。这是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";


10-07 19:45
查看更多