gpt4 book ai didi

c# - 类似值的 GetHashCode

转载 作者:行者123 更新时间:2023-11-30 22:15:10 27 4
gpt4 key购买 nike

我有以下类(class):

public class Foo
{
int year;
string name;
int category;
}

这是一些示例数据:

2012    Test1   1000
2012 Test2 1000
2012 Test3 1000
2012 Test4 1000
2012 Test4 10
...

如果我覆盖 GetHashCode 所有结果都非常相似:

return year ^ name ^ category;

int hash = 13;
hash = hash * 33 + year.GetHashCode();
hash = hash * 33 + name.GetHashCode();
hash = hash * 33 + category.GetHashCode();
return hash;

对于这种情况,什么是好的哈希函数(具有最大分布)?

编辑:也许我对哈希桶的理解是错误的。将相似的哈希值转到同一个桶?

"Test1".GetHashCode() --> -1556460260
"Test2".GetHashCode() --> -1556460257

最佳答案

我建议的一件事是检查字符串对象是否为空

实现似乎没问题,应该是相似的,但哈希码应该不同,因为主要目标是使它们落入不同的桶中,从而有助于进一步的操作。

   public int hashCode() {    // Assuming year and category are String like name.
int hash = 31;
hash = hash * 331 + (this.year != null ? this.year.GethashCode() : 0);
hash = hash * 331 + (this.name != null ? this.name.GethashCode() : 0);
hash = hash * 331 + (this.category != null ? this.category.GethashCode() : 0);

return hash;
}

我在重写 hashCode 时学到的几个步骤是;

  1. Choose a prime hash e.g. 5, 7, 17 or 31 (prime number as hash, results in distinct hashcode for distinct object).
  2. Take another prime as multiplier different than hash is good.
  3. Compute hashcode for each member and add them into final hash. Repeat this for all members which participated in equals.
  4. Return hash.

关于c# - 类似值的 GetHashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18127155/

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