且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

GetHash code相似的价值观

更新时间:2023-02-27 09:28:07

有一件事我会建议是检查字符串对象为null 或没有。

的实施似乎要被罚款,这将是类似的,但散列codeS应该是不同的主要目的是让他们在不同的水桶土地,从而帮助了进一步的操作。

 公众诠释哈希code(){//假设一年和类别都是字符串,如姓名。
    INT哈希= 31;
    哈希散列= * 331 +(!?this.year = NULL t​​his.year.Gethash code():0);
    哈希散列= * 331 +(!?this.name = NULL t​​his.name.Gethash code():0);
    哈希散列= * 331 +(!?this.category = NULL t​​his.category.Gethash code():0);

    返回哈希;
}
 

我学到同时覆盖散列code中的几个步骤;

  
      
  1. 选择一个黄金散列如5,7,17或31(素数为乱码,导致不同的散列code代表不同的对象)。
  2.   
  3. 在拍摄另一主要作为乘数比哈希不同的是不错的。
  4.   
  5. 在计算哈希值code的每个成员,并将它们添加到最终的哈希值。重复此为其参与平等的所有成员。
  6.   
  7. 返回哈希值。
  8.   

I have the following class:

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

Here is some example data:

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

If I override GetHashCode all results are very similiar:

return year ^ name ^ category;

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

What is a good hash function (with maximal distribution) for this situation?

Edit: Perhaps my understanding of the hash buckets is wrong. Go similar hash values to the same bucket?

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

One of the things I would recommend is to check if the String object is null or not.

The implementation seems to be fine, it would be similar but the hashcodes should be different as the main objective is to make them land in different buckets, hence helping out for further operations.

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

The few steps that I have learnt while Overriding hashCode are;

  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.