java - 在java中实现好的hashCode函数?

标签 java hashcode hash-collision hash-code-uniqueness

我现在知道有内置实用程序,例如 Apache commons lang 中的 HashCodeBuilder,但我试图了解如何自己实现它,并在 http://en.wikipedia.org/wiki/Java_hashCode() 遇到了 Employee 类的 hascode 函数的示例。

谷歌上的任何地方都建议使用相同的技术,例如将非零值与奇素数相乘,然后将其相加 与实例变量(为实例变量执行此操作)。

问题:-

1)为什么我们不能将employeeId作为hascode返回,因为它永远是唯一的。它很简单并且服务于 hascode 目的。 同意,如果它不是唯一的,我们可能需要这种技术。是这样吗?

2)即使员工 ID 不唯一,为什么建议乘以奇数素数?为什么取任何该死的整数都不是 算不错吗?

更新:-

Peter 我运行了你提到的打印示例

[0、32、64、96、128、160、192、224、288、256、352、320、384]

[0、32、64、96、128、160、192、224、288、256、352、320、384]

i assume that output for now as yoy expected to understand the concept as you mentioned in your answer

[373、343、305、275、239、205、171、137、102、68、34、0]

[0、34、68、102、137、171、205、239、275、305、343、373]

正如您在评论中所建议的,该示例演示了即使是唯一的哈希码也可以最终出现在同一个存储桶中。这怎么办 例子证明了这种行为?您的意思是整数 373 和整数 0 2 最终在同一个存储桶中吗?

素数在这个例子中有何帮助,而 34 又有何帮助?

最佳答案

why we can't return employeeId as hascode becoz it will aways be unique. Its simple and serves the hascode purpose. Agreed if it is not unique probably we need that kind of technique. Is that right?

它的独特性并不重要。乘以素数是将多个字段合并为一个 hashCode 的好方法,但听起来好像只有一个,所以不会有太大区别。

Even If employee id is not unique, why its suggested to multiply with odd prime number? why taking any damn integer is not considered good?

如果乘以偶数,hashCode 的最低位是多少?它有多随机/有用?

<小时/>

注意:Integer 的每个 hashCode() 都是唯一的,但是获得整数值的正确组合,当它们减少到 HashMap 的容量时,它们实际上映射到同一个存储桶。在此示例中,条目以与添加顺序相反的顺序显示,因为每个条目都映射到同一个存储桶。

HashSet<Integer> integers = new HashSet<>();
for (int i = 0; i <= 400; i++)
    if ((hash(i) & 0x1f) == 0)
        integers.add(i);
HashSet<Integer> integers2 = new HashSet<>();
for (int i = 400; i >= 0; i--)
    if ((hash(i) & 0x1f) == 0)
        integers2.add(i);
System.out.println(integers);
System.out.println(integers2);


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);
}

打印

[373, 343, 305, 275, 239, 205, 171, 137, 102, 68, 34, 0]
[0, 34, 68, 102, 137, 171, 205, 239, 275, 305, 343, 373]

关于java - 在java中实现好的hashCode函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19209464/

相关文章:

数据库为空时 Java 崩溃

java - 如何检查数组中的元素是否按照出现次数排序?

java - 一个 URI 模板形式的路径变量数量不受限制

java - 如何在哈希冲突后检索值

md5 - 递归MD5和碰撞概率

java - Java 编译时生成枚举

java - HashMap 优化的影响,将与每个条目关联的哈希代码缓存到其 get 方法

java - 如何从 String.hashCode() 值获取字符串?

java - HashMap 的 containsKey 方法返回 false,但它的键是 integer[] 类型?

java - 短字符串的哈希码可以相同吗?