if("String ".intern().trim()=="String"){
System.out.println("Equals");
}else{
System.out.println("Unequal");
}
上面的代碼顯示Unequal
。我不明白爲什麼?有人可以解釋嗎?爲什麼我的字符串比較的下面的代碼沒有顯示我期待在java
if("String ".intern().trim()=="String"){
System.out.println("Equals");
}else{
System.out.println("Unequal");
}
上面的代碼顯示Unequal
。我不明白爲什麼?有人可以解釋嗎?爲什麼我的字符串比較的下面的代碼沒有顯示我期待在java
始終使用equals()
方法比較字符串!!!
嘗試這樣:
if("String ".trim().equals("String")){
System.out.println("Equals");
}else{
System.out.println("Unequal");
}
有用的鏈接
"String".intern()
創建存儲在permgen或metaspace中的字符串的另一個實例,而原始實例存儲在常規堆中。因此你的比較永遠是錯誤的。
字符串常量也被攔截。 – Puce
是的,他們是。我立場糾正。 –
你需要知道字符串字面被放置在字符串池默認情況下,像
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
方法其中,如果指定到子
new String
對象return this;
因此,在您的代碼中,您正試圖將"String "
在字符串池中(您不必這樣做,因爲您正在使用字符串文字"String "
,它已經放置在池中),那麼您在此對象上使用trim
方法,因爲有部分要修剪,所以它會創建並返回與原始字符串不同的新字符串,並且絕對不是來自字符串池,因此將其與"String"
字面值對比==
將返回false
。
我真的不知道你面對什麼,但如果你想使用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
我沒有做任何Java,而是因爲我每週看這樣一個問題上是這樣,我知道你不應該使用'=='比較字符串,而是使用'.equals()':-) –
@Bartdude我認爲這是一個關於interned字符串的問題 - 所以問題是有效的。 – Puce
@Puce問題是比較的右側沒有被執行 - 因此它永遠不會等於左側的實例化表單。 –