writing own GetHashCode() function

  • Thread starter Thread starter RAM
  • Start date Start date
RAM said:
Hello,
I would like to ask programmers such question:
I have a class containing a few fields:
int i;
string a;
bool b;
int j;
bool q;
decimal d;
I need to write GetHashCode function for this class. Could you suggest
me some idea? Maybe I can should use one of the following solutions:

http://en.wikipedia.org/wiki/List_of_hash_functions#Cyclic_redundancy_checks

I tend to use the following approach, as recommended by Josh Bloch in
"Effective Java":

int hash = 23;
hash = hash*37 + i;
hash = hash*37 + a.GetHashCode();
hash = hash*37 + (b ? 1 : 0);
hash = hash*37 + j;
hash = hash*37 + (q ? 1 : 0);
hash = hash*37 + d.GetHashCode();
return hash;

The 23 and 37 are preferrably prime numbers (or at least coprime) but I
don't think it matters too much what they are apart from that.
 
RAM said:
Hello,
I would like to ask programmers such question:
I have a class containing a few fields:
int i;
string a;
bool b;
int j;
bool q;
decimal d;
I need to write GetHashCode function for this class. Could you suggest
me some idea?

Depends on what you're actually storing. Quick and dirty could be:

return (i + "$" + a + "$" + b + "$" + j + "$" + q + "$" + d).GetHashCode();

Alun Harford
 
I suggest:

return i.GetHashCode() ^ a.GetHashCode() ^ b.GetHashCode() ^ etc.

That has issues for symmetry reasons. Consider the simple Point:

class Point
{
int x;
int y;
}

(They could be doubles, etc - all accessors etc removed.)

Using a hash built from x ^ y means that:

1) All points where x=y have the same hash - and they're not hugely
unlikely in the real world

2) A point (x, y) has the same hash as the point (y, x) which is again
not terribly unlikely to come up.
 
Hi Jon,

I never thought about it. BTW we use floats and it becomes quite
unlikely.

Thanks for your post.

Alberto
 
Back
Top