测试/评测java hashmap的hashcode函数
如何在Java中测试/评测hashCode()实现?i、 e.我的测试数据是否分布合理、均匀等?java API本身有什么简单的方法吗?测试/评测java hashmap的hashcode函数,java,collections,hashmap,Java,Collections,Hashmap,如何在Java中测试/评测hashCode()实现?i、 e.我的测试数据是否分布合理、均匀等?java API本身有什么简单的方法吗?Map hashCodes=new HashMap(); Map<Integer, Integer> hashCodes = new HashMap<Integer, Integer>(); for (YourHashcodedClass testData: largeCollectionOfTestData) { Integer
Map hashCodes=new HashMap();
Map<Integer, Integer> hashCodes = new HashMap<Integer, Integer>();
for (YourHashcodedClass testData: largeCollectionOfTestData) {
Integer hashCode = Integer.valueOf(testData.hashCode());
Integer occurrences = hashCodes.get(hashCode);
if (occurrences == null) {
occurrences = 0;
}
hashCodes.put(hashCode, occurrences+1);
}
对于(YourHashcodedClass测试数据:largeCollectionOfTestData){
整数hashCode=Integer.valueOf(testData.hashCode());
整数出现次数=hashCodes.get(hashCode);
如果(出现次数==null){
出现次数=0;
}
hashCodes.put(hashCode,出现次数+1);
}
然后分析您的映射是否存在冲突。老实说,如果您遵循最佳实践,您不必分析或测试
hashCode()
方法的分布。请参阅下面的哈希代码配方。此外,即使编写得不太好,HashMap
实现也会重新生成结果以减少冲突:
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
您还可以使用from为您构建哈希代码
- 在名为
的result
变量中存储一些常量非零值,例如17int
- 为每个字段计算一个
hashcodeint
:c
- 如果字段是布尔值,则计算
(f?1:0)
- 如果字段是一个
,则计算字节、字符、短字符、int
(int)f
- 如果字段是长的,则计算
(int)(f^(f>>32))
- 如果字段是一个
,则计算float
float.floatToIntBits(f)
- 如果该字段是一个
,请计算double
,然后像上面一样对结果的double.double到longbits(f)
进行散列long
- 如果字段是对象引用,并且此类的
方法通过递归调用equals
来比较字段,则递归调用字段上的equals
。如果该字段的值为hashCode
,则返回0null
- 如果字段是数组,则将其视为每个元素都是单独的字段。如果数组字段中的每个元素都是重要的,则可以使用1.5版中添加的
方法之一数组.hashCode
- 如果字段是布尔值,则计算
- 将hashcode
组合成c
,如下所示:result
result=31*result+c代码>