第一重写写equal:1.判断地址值,一样为true。2.判断length不一样,为false,长度一样,再判断每一个char【】数组,for遍历对比,全部一样为true,否则为false。
`1 public boolean equals(Object anObject) {
2 if (this == anObject) {
3 return true;
4 }
5 if (anObject instanceof String) {
6 String anotherString = (String) anObject;
7 int n = value.length;
8 if (n == anotherString.value.length) {
9 char v1[] = value;
10 char v2[] = anotherString.value;
11 int i = 0;
12 while (n-- != 0) {
13 if (v1[i] != v2[i])
14 return false;
15 i++;
16 }
17 return true;
18 }
19 }
20 return false;
21 }
`
第二重写hashcode:为int类型,大小为:-231-1~~231-1。由源码可以看出String越长,hashcode值越大,达到最大,就变成负数,又重新排。
public int hashCode() {
int h = hash; //Default to 0 ### String类中的私有变量,
if (h == 0 && value.length > 0) { //private final char value[]; ### Sting类中保存的字符串内容的的数组
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}