为什么intern方法在java中不返回相等的字符串

为什么intern方法在java中不返回相等的字符串,java,Java,根据我的理解,第一次调用intern方法应该创建一个带有单个字符串的“字符串intern池”“hello”。对intern方法的第二次调用将不会起任何作用(因为池中已经存在“hello”字符串)。现在,当我说s1==s2时,我希望JVM比较string intern pool中的“hello”字符串并返回true,您只是在检查引用堆中不同对象的原始字符串。 您没有存储方法的返回值 应该是 public static void main (String[] args) { String

根据我的理解,第一次调用intern方法应该创建一个带有单个字符串的“字符串intern池”
“hello”
。对intern方法的第二次调用将不会起任何作用(因为池中已经存在
“hello”
字符串)。现在,当我说
s1==s2
时,我希望JVM比较string intern pool中的
“hello”
字符串并返回
true

,您只是在检查引用堆中不同对象的原始字符串。 您没有存储方法的返回值

应该是

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 ?


}
返回一个新的插入字符串。要更改
s1
s2
,您需要

String s1 = new String("hello");
String s2 = new String("hello");
String s11 = s1.intern();
String s22 = s2.intern();
System.out.println(s11 == s22); // returns true
s1==s2
然后将返回true。

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

s1 = s1.intern();
s2 = s2.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
}
如果打印S1的值,它将只打印“Hello”。但如果你这样写:

String S1= "Hello";
S1.concat("World");
然后它将打印“Hello World”

同样,您需要将值指定为:

S1=S1.concat(" World");
如果比较s1==s2,它将返回真值,但假设:

s1=s1.intern();
s2=s2.intern();

如果比较s3==s4,则为真,但(s3==s1)和(s4==s2)为假。

Wow答案已准备就绪,只是等待所有站点以写入模式返回。因为您没有比较String.intern()返回的值,你对这种比较应该如何进行的期望完全缺乏依据。仅仅因为这是一个关于String.intern的问题并不意味着这是一个dup。在这种情况下,OP认为intern对调用它的字符串有影响。另一个问题是关于String.intern的完全不同的问题。
String s3=s1.intern();
String s4=s2.intern();