2014-02-06 10 views
-2
if("String ".intern().trim()=="String"){ 
    System.out.println("Equals"); 
}else{ 
    System.out.println("Unequal"); 
} 

上面的代碼顯示Unequal。我不明白爲什麼?有人可以解釋嗎?爲什麼我的字符串比較的下面的代碼沒有顯示我期待在java

+4

我沒有做任何Java,而是因爲我每週看這樣一個問題上是這樣,我知道你不應該使用'=='比較字符串,而是使用'.equals()':-) –

+3

@Bartdude我認爲這是一個關於interned字符串的問題 - 所以問題是有效的。 – Puce

+0

@Puce問題是比較的右側沒有被執行 - 因此它永遠不會等於左側的實例化表單。 –

回答

0

始終使用equals()方法比較字符串!!!

1

"String".intern()創建存儲在permgen或metaspace中的字符串的另一個實例,而原始實例存儲在常規堆中。因此你的比較永遠是錯誤的。

+0

字符串常量也被攔截。 – Puce

+0

是的,他們是。我立場糾正。 –

2

你需要知道字符串字面被放置在字符串池默認情況下,像

String s = "Hello";//this will be in string pool 

而是通過new String(...)在運行時創建的字符串是不是默認設置或檢索到這個地址池中。

String s2 = new String(s);// or even `new String("Hello")` 
System.out.println(s == s2);// returns false, which means s2 holds different String 
          // object then from String pool 

現在substring回報new String(...)對象,所以這意味着它們不是從字符串池。

trim內部使用substring方法其中,如果指定到子

  • 範圍會比不同於0直到長度將與字符從指定範圍內的返回new String對象
  • 範圍是從0至串長度(理想涵蓋整個字符串)返回相同的字符串與return this;

因此,在您的代碼中,您正試圖將"String "在字符串池中(您不必這樣做,因爲您正在使用字符串文字"String ",它已經放置在池中),那麼您在此對象上使用trim方法,因爲有部分要修剪,所以它會創建並返回與原始字符串不同的新字符串,並且絕對不是來自字符串池,因此將其與"String"字面值對比==將返回false

3

我真的不知道你面對什麼,但如果你想使用intern()方法將字符串的地址比較,這也將工作:

if ("String ".trim().intern() == "String") { 
    System.out.println("Equals"); 
} else { 
    System.out.println("Unequal"); 
} 

你只需要調換呼叫trim()intern()

intern()搜索這已經是在堆和地址此字符串。當您使用==比較字符串時,地址將相等。

以便更好地觀察:

Value       Evaluates to Address Explanation 
"String"      "String"  1   Creates new "String" 
"String "      "String "  2   Creates new "String " 
"String ".trim()    "String"  3   trim() creates new "String" 
"String ".trim().intern()  "String"  1   intern() finds the already created "String" 
"String ".intern()   "String "  2   intern() finds the already created "String " 
"String ".intern().trim()  "String"  4   trim() creates new "String" 

這也是因爲trim()正在生成new String()

試圖通過自己:

public class StringCompare { 
    public static void main(String[] args) { 
     System.out.println(System.identityHashCode("String")); 
     System.out.println(System.identityHashCode("String ")); 
     System.out.println(System.identityHashCode("String ".trim())); 
     System.out.println(System.identityHashCode("String ".trim().intern())); 
     System.out.println(System.identityHashCode("String ".intern())); 
     System.out.println(System.identityHashCode("String ".intern().trim())); 
    } 
} 

將輸出類似:

1500673861  // 1 
1777631459  // 2 
859434349  // 3 
1500673861  // 1 
1777631459  // 2 
538093921  // 4 
+0

或只是省略修剪()我這種情況;-) – Puce

+0

不,因爲第一個字符串在最後有一個空格!看見? ;) – bobbel

+0

啊,我真的錯過了。抱歉! – Puce

相關問題