private final char value[];
private int hash; // Default to 0 public String(String original) {
this.value = original.value;
this.hash = original.hash;
} public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
} String:
|--CompareTo
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;
} |--equals
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;
} |--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;
} //toString的经典实现
public static String toString(int[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]"; StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {//中间省略判断,提高效率
b.append(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}