为什么intern方法不会在java中返回相等的String

use*_*698 5 java

public static void main (String[] args) {

    String s1 = new String("hello");
    String s2 = new String("hello");
    s1.intern();
    s2.intern();        
    System.out.println(s1 == s2); // why this returns false ?


}
Run Code Online (Sandbox Code Playgroud)

根据我的理解,第一次调用实习方法应该创建一个带有单个字符串的"字符串实习池" "hello".第二次调用实习方法没有做任何事情(因为"hello"字符串已经存在于池中).现在,当我说s1 == s2我希望JVM比较"hello"字符串实习池中的字符串并返回时true.

Mur*_*nik 4

intern()方法不会修改字符串,只是从字符串池中返回对应的字符串。因此,由于您没有保留返回值,因此您的调用intern()毫无意义。但是,如果您实际使用它们,您会发现两者都指向完全相同的字符串:

public static void main (String[] args) {
    String s1 = new String("hello");
    String s2 = new String("hello");
    s1 = s1.intern();
    s2 = s2.intern();        
    System.out.println(s1 == s2); // will print true
}
Run Code Online (Sandbox Code Playgroud)