/** Cache the hash code for the string */
private int hash; // Default to 0
//String類將hashCode()的結果緩衝為hash值,提高效能。 從這裡可知:String的hash值是從0開始算的,然後根據字元數組計算出來
//equals方法實現方式
//String對象equals()相等的條件是二者同為String對象,長度相同,且字串值完全相同;不要求二者是同一個對象。
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;
}
//這裡可以看出來String值的hash值的計算方法
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;
}
//String str=new string("str");這種方式構造出來的字串和單獨的字面量"str"一定相等的,因為他們的值以及hash值都是相等的
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
測試類別
import org.junit.Test;
public class test
{
Object obj=new Object();
String str=new String("123");
@Test
public void test(){
System.out.println(obj.hashCode());
System.out.println("\"123\".hashCode():"+"123".hashCode());
System.out.println(str.hashCode());
int h=0;
for(int i=0;i<"123".length();i++){
char [] val="123".toCharArray();
h=h*31+val[i];
}
System.out.println("h:"+h);
}
}