很多人指出hashCode()方法是怪的。它只产生了大约20,000个代码,用于2600万个不同的对象。这是平均每个散列桶1,300个对象=非常非常糟糕。然而,如果我把两个数组转换为一个数字在基地52我保证获得一个唯一的哈希码为每个对象:
public int hashCode() {
// assume that both a and b are sorted
return a[0] + powerOf52(a[1], 1) + powerOf52(b[0], 2) + powerOf52(b[1], 3) + powerOf52(b[2], 4);
}
public static int powerOf52(byte b, int power) {
int result = b;
for (int i = 0; i < power; i++) {
result *= 52;
}
return result;
}
对数组进行排序,以确保此方法满足hashCode()约定,等于对象具有相同的哈希码。使用旧方法,每秒100,000次投放,100,000到2,000,000次的平均投入量是:
168350.17
109409.195
81344.91
64319.023
53780.79
45931.258
39680.29
34972.676
31354.514
28343.062
25562.371
23850.695
22299.22
20998.006
19797.799
18702.951
17702.434
16832.182
16084.52
15353.083
使用新方法给出:
337837.84
337268.12
337078.66
336983.97
313873.2
317460.3
317748.5
320000.0
309704.06
310752.03
312944.5
265780.75
275540.5
264350.44
273522.97
270910.94
279008.7
276285.5
283455.16
289603.25
好多了。旧的方法非常快地结束,而新的方法保持了良好的吞吐量。