Java爬坑日誌:關於equals()和一個StringBuffer進行比較
在做登陸註冊功能時遇到的問題:將傳入的密碼和數據庫中保存的加密密碼進行比較時遇到,將兩個字符串打印出來,長度相同說明沒有隱藏的字符,開始考慮是不是編碼問題,檢查了一下發現都不是。最後問題定位在String.equals()方法上:
//看看equals的源碼:
/**
* Compares this string to the specified object. The result is {@code
* true} if and only if the argument is not {@code null} and is a {@code
* String} object that represents the same sequence of characters as this
* object.
*
* @param anObject
* The object to compare this {@code String} against
*
* @return {@code true} if the given object represents a {@code String}
* equivalent to this string, {@code false} otherwise
*
* @see #compareTo(String)
* @see #equalsIgnoreCase(String)
*/
public boolean equals(Object anObject) {
//傳入的是object,所以使用StringBuffer沒有報錯。
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
//掃描,將StringBuffer強轉String
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
問題在這,也是自己不熟練的問題,傳入的StringBuilder,而不是String。直接改爲StringBuilder.toString();
這裏還有一種方式:
//直接帶編碼的方式處理字符串,解決問題
String str=new String(string.getBytes(),"UTF-8");