1. 程式人生 > >不同類中的hashCode方法

不同類中的hashCode方法

1、Object的hashCode( )

public class Object{
        public native int hashCode();  
}

大家看到了,爸爸類Object提供了一個本地方法,返回值型別為int,奮鬥過程交給了兒子類。

2、String類的hashCode( )

public int hashCode() {
	int h = hash;
	if (h == 0 && value.length > 0) {
		hash = h = isLatin1() ? StringLatin1.hashCode(value) : StringUTF16.hashCode(value);
	}
	return h;
}
private boolean isLatin1() {
	return COMPACT_STRINGS && coder == LATIN1;
}

再看,String類hashCode方法居然想返回雜湊碼(hash)!那些看不懂從哪裡來的詞都是String內部的變數和方法。經過一系列的*&&%%^以後,hashCode返回雜湊碼,作用是什麼?以後寫集合框架的時候再說。

3、Integer類的hashCode( ),數值型類以它為例。

public int hashCode() {
	return Integer.hashCode(value);
}

public static int hashCode(int value) {
	return value;
}

大家看到了,Integer不僅重寫了,還自己過載了,呼叫Integer的hashCode( )方法直接返回它的int值。比起String來,這個類是真的懶。

4、HashMap類的hashCode( )

public final int hashCode() {
	return Objects.hashCode(key) ^ Objects.hashCode(value);
}
public static int hashCode(Object o) {
	return o != null ? o.hashCode() : 0;
}