Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/367.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
测试/评测java hashmap的hashcode函数_Java_Collections_Hashmap - Fatal编程技术网

测试/评测java hashmap的hashcode函数

测试/评测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

如何在Java中测试/评测hashCode()实现?i、 e.我的测试数据是否分布合理、均匀等?java API本身有什么简单的方法吗?

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
    int
    变量中存储一些常量非零值,例如17
  • 为每个字段计算一个
    int
    hashcode
    c
    • 如果字段是布尔值,则计算
      (f?1:0)
    • 如果字段是一个
      字节、字符、短字符、int
      ,则计算
      (int)f
    • 如果字段是长的,则计算
      (int)(f^(f>>32))
    • 如果字段是一个
      float
      ,则计算
      float.floatToIntBits(f)
    • 如果该字段是一个
      double
      ,请计算
      double.double到longbits(f)
      ,然后像上面一样对结果的
      long
      进行散列
    • 如果字段是对象引用,并且此类的
      equals
      方法通过递归调用
      equals
      来比较字段,则递归调用字段上的
      hashCode
      。如果该字段的值为
      null
      ,则返回0
    • 如果字段是数组,则将其视为每个元素都是单独的字段。如果数组字段中的每个元素都是重要的,则可以使用1.5版中添加的
      数组.hashCode
      方法之一
  • 将hashcode
    c
    组合成
    result
    ,如下所示:
    result=31*result+c

地图包含您的哈希代码。任何出现次数大于1的条目都是碰撞。