不同類型底層的hashCode方法
Integer
public static int hashCode(int value) {
return value;//返回的就是底層包裝的基本數(shù)據(jù)類型int對應的數(shù)值value
}
Double
public int hashCode() {
return Double.hashCode(value);
}
public static int hashCode(double value) {
long bits = doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
}
String
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;
}
自定義類Student
public static int hashCode(Object a[]) {
if (a == null)
return 0;
int result = 1;
for (Object element : a)
result = 31 * result + (element == null ? 0 : element.hashCode());
return result;
}
如何減少沖突?
- 將主數(shù)組 長度變大
- 優(yōu)化計算位置的函數(shù)衅檀。
- hashCode()和equals()方法調(diào)用幾次,什么時候調(diào)用?
- hashCode每次都調(diào)用十偶,equals只有在沖突的時候(在同一位置)上,才調(diào)用园细。