2016-11-21 104 views
-3

Javadoc说如果在字符串池中有一个相等的String,那么intern()方法将返回String。在intern()方法后比较两个相等的字符串

public class Demo { 
public static void main(String[] args) { 
    String str1 = "Apple"; 
    String str2 = new String("Apple"); 

    System.out.println(str1.intern() == str2); //false 
    System.out.println(str1 == str2.intern()); //true 
} 
} 

我希望在这两种情况下都能成立。

+0

[这个答案](http://stackoverflow.com/a/40480291/)(以稍微不同的问题)说明了一切你问过。 –

+0

我假设你明白'str1 == str2'会返回false;那么,假设'str1'被分配了字符串字面值,[Javadoc](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#intern())描述那'str.intern()== str1'。因此,'str1.intern()== str2'与'str1 == str2'相同,因此它是错误的。 –

回答

0

这样做str1.intern()带来什么你试试... 由于str1是字符串(将inmediatly放置在字符串池中),并且要针对它在堆上分配的str2比较吧。 ..

因此

System.out.println(str1.intern() == str2); 

将打印false,你是比较在stirng池VS堆上一个字符串的字符串的参考...

2
System.out.println(str1.intern() == str2); //false 

在上述情况下,您将interned字符串"Apple"的引用与堆中另一个字符串(但具有相同值)的引用的引用进行比较。所以,结果是“假”。

System.out.println(str1 == str2.intern()); //true 

在上述情况下,你是比较字符串常量的参考池,通过试图“苹果”添加到字符串常量池中有一个参考。 SInce,“Apple”已经在第一行,这个实习将返回str1指向的对象。因此你变得真实。

PS:此行为在javadoc

0

String.intern()方法描述用于创建heapString对象在String常量池的精确副本。在String常量池中的String objects自动扣留,但heapString对象不

System.out.println(firstString.intern() == secondString);//false because it will fetch exact copy of the string compare in string 

System.out.println(firstString == secondString.intern());//True because it will compare firstString with fetch the second String it will check heap or not