c# - GetHashCode for similar values -


i have following class:

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

here example data:

2012    test1   1000 2012    test2   1000 2012    test3   1000     2012    test4   1000 2012    test4   10 ... 

if override gethashcode results 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 hash function (with maximal distribution) situation?

edit: perhaps understanding of hash buckets wrong. go similar hash values same bucket?

"test1".gethashcode() --> -1556460260 "test2".gethashcode() --> -1556460257 

one of things recommend check if string object null or not.

the implementation seems fine, similar hashcodes should different main objective make them land in different buckets, hence helping out further operations.

   public int hashcode() {    // assuming year , category string 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 have learnt while overriding hashcode are;

  1. choose prime hash e.g. 5, 7, 17 or 31 (prime number hash, results in distinct hashcode distinct object).
  2. take prime multiplier different hash good.
  3. compute hashcode each member , add them final hash. repeat members participated in equals.
  4. return hash.

Comments

Popular posts from this blog

matlab - Deleting rows with specific rules -

php - MySQLi multi_query results for later use -