gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:40:19 25 4
gpt4 key购买 nike

我现在知道有内置实用程序,例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com