我有以下問題:我有一個字符串,我從MySQL數據庫(使用JDBC驅動程序)讀取,並且必須將它與通過TCP接收的另一個字符串(BufferedReader
)進行比較。當我使用String.equals
時,即使字符串完全相等,也會返回false,我甚至會將兩個字符串都打印到控制檯,以確保沒有任何拼寫錯誤或null對象。 String.compareTo
返回-100左右的負數。Java兩個相等的字符串不相等
我真的很困惑,並沒有具體的想法如何解決這個問題。也許它與數據庫的編碼(UTF-8)有關?
按照要求,這裏是我的代碼片段:
public TeleportSign getTeleportSign(String target) {
// I used a HashMap, but I switched to an ArrayList in order to be able
// to compare the Strings directly.
//return signs.get(target);
for(TeleportSign s : signsList) {
// I am printing the Strings here. I even put stars to the left
// and the right of the String to make sure there are no
// spaces or new lines. s.getTarget() returns the String from the DB,
// target is the String sent over TCP.
System.out.println("*" + s.getTarget() + "* " +
String.valueOf(s.getTarget().compareTo(target))
+ " *" + target + "*");
if(s.getTarget().compareTo(target) == 0)
return s;
}
return null;
}
和控制檯輸出爲:提前
*TDM1* -84 *TDM1*
謝謝! 隊長
什麼是字符串值請添加代碼片段 –
什麼是兩個字符串值? – Bathsheba
打印出兩個字符串中每個字符的數字字符值。你會注意到他們僅僅*看起來就像未經訓練的眼睛! – Kayaman