1,equals().
“abd”.equals(“abc”)采取的是兩字符串長度相等,在相等情況下,分別賦值給兩字節數組,循環數組,如對應位置兩數組值不相等,則return false;如都相等,則 return true. 源碼如下:
public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof 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;}2, hashcode().Stringstr=”ab”;
str.hashcode()==3105==(0*31+97)*31+98 //其中 97=a;98=b. a對應的ascii碼=97。
把字符串分成字符數組,
用一個初始值為零的值,按公式 h=31*h+chararray[i] 在遍歷該字符串時候,重復計算,最后的h值就是該字符串數組的hashcode()返回值。 源碼如下:
public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
新聞熱點
疑難解答