What is the best way of combining two uints into an int for overridding GetHashCode()?
I have a class where I have overridden Equals based on two uint values. Because I have overridden Equals I need to override GetHashCode.
The one uint value represents an id that should never have a duplicate. It will not necessarily be an auto-incrementing int value but should be in most cases. The second uint value represents a type field for the object.
Using only the ID field should be enough. But it might be a little restrictive in some cases which is why i wanted to combine the ID and the type.
I thought of adding the two numbers together an开发者_如何学JAVAd then combining the high order bits with the lower order bits using XOR.
Any other ideas?
The hash code is only used to distribute items in hash based collections like a Dictionary
, so the hash code should ideally produce as few collisions as possible.
The minimum requirement is however only that the hash code should always be the same for any given set of values. Therefore even this is a valid hash code algorithm:
public int GetHashCode() {
return 1;
}
Eventhough it gives a horrible distribution, it's still functional.
If you want to use both the Id and Type in the hash code, you can just xor them together:
public int GetHashCode() {
return (int)Id ^ (int)Type;
}
If you know that there will never (or rarely) be a duplicate id
then you can just use that.
But in general to get a good HashCode for two ints a
and b
you can choose a small prime p
and calculate a + p * b
.
精彩评论