I am trying to create a quick hashcode function for a complex number class (a + b)
in C#.
I have seen repeatedly the a.GetHashcode()^b.GetHashCode()
method. But this will give the same hashcode for (a,b)
and (b,a)
.
Are there any standard algorithm to do this and are there any functions in the .Net framework to help?
If you use eclipse, you can generate equals() and hashCode() using: Source -> Generate hashCode() and equals(). Using this function you can decide which fields you want to use for equality and hash code calculation, and Eclipse generates the corresponding methods.
hashcode() is computed via jvm argument -XX:hashCode=N where N can be a number from [0-5]... Depending on an application you may see unexpected performance hits when .
Combines two values into a hash code.
A hash code is an integer value that is associated with each object in Java. Its main purpose is to facilitate hashing in hash tables, which are used by data structures like HashMap.
My normal way of creating a hashcode for an arbitrary set of hashable items:
int hash = 23; hash = hash * 31 + item1Hash; hash = hash * 31 + item2Hash; hash = hash * 31 + item3Hash; hash = hash * 31 + item4Hash; hash = hash * 31 + item5Hash; // etc
In your case item1Hash
could just be a
, and item2Hash
could just be b
.
The values of 23 and 31 are relatively unimportant, so long as they're primes (or at least coprime).
Obviously there will still be collisions, but you don't run into the normal nasty problems of:
hash(a, a) == hash(b, b) hash(a, b) == hash(b, a)
If you know more about what the real values of a
and b
are likely to be you can probably do better, but this is a good initial implementation which is easy to remember and implement. Note that if there's any chance that you'll build the assembly with "check for arithmetic overflow/underflow" ticked, you should put it all in an unchecked block. (Overflow is fine for this algorithm.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With