2016-11-21 83 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