final class String {算法
1 空串的檢查this
public boolean isEmpty() {
return value.length == 0;
}hash
2 相等class
public boolean equals(Object anObject) {
if (this == anObject) { //Identifical reference
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;
}im
3 比大小
while
public int compareTo(String anotherString) {
int len1 = value.length;
int len2 = anotherString.value.length;
int lim = Math.min(len1, len2);
char v1[] = value;
char v2[] = anotherString.value;
int k = 0;
while (k < lim) {
char c1 = v1[k];
char c2 = v2[k];
if (c1 != c2) {
return c1 - c2; //第一個相異的字符大小表明串的大小。
}
k++;
}
return len1 - len2; //沒有相異的, 長串比短串大
}co
4 Hash字符
public int hashCode() {
int h = hash; //初始值。
if (h == 0 && value.length > 0) { //h == 0用於狀態。避免重複計算。
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i]; // 經典算法 y = k * x + b, 線性映射。 k = 31 爲素數。
}
hash = h;
}
return h;
}return
...