1. hashCode()方法
2. equals 方法
1.hashCode 方法是Object中的一个方法 ,String 类对其进行了重写,主要是不断的对前一个字符所产生的hash值进行累加。
public int hashCode() {
int h = hash;//String 类中的hash
if(h == 0 && value.length > 0) {// 判断字符串长度是大于0的
char[] val = value;
for(int i=0; i < value.length; i++) {
h = 31 * h + char[i];
}
hash = h;
}
return h;
}
2.equals 方法
equals 方法是Object的一个方法,在String 类中对其进行了重写,具体代码如下。
public boolean equals(Object anObject){
if(this == anObject) {
return true;
}
if(anObject isInstanceOf String) {
String anString = (String)anObject;
int n = value.length;
if(n == anString.value.length) {
char[] strA = value;// 字符串是以char类型的数组存在的
char[] strB = anString.value;
int i = 0;
while(lengthA-- != 0) { // 由于String类中字符串是以char数组来存储的,因此,比较数组中的每一个元素即可
if(strA[i] != strB[i]) {
return false;
}
i++;
}
return true;
}
return false;
}
}