Why is the xor operator used in computing hash code?
This question already has an answer here:
The ^
operator is the bitwise exclusive-or operator.
In this case it's being used as a convenient way to generate a hash code from three integers. (I don't think it's a very good way, but that's a different issue...)
Weirdly, after constructing a hash code, they use GetHashCode()
on it again, which is utterly pointless for an int because it will just return the int itself - so it's a no-op.
This is how they should have written it:
public override int GetHashCode(Box bx)
{
return bx.Height ^ bx.Length ^ bx.Width;
}
This SO answer explains why XOR works quite well sometimes: Why are XOR often used in java hashCode() but another bitwise operators are used rarely?
Note: The reason I don't like using xor for a hash code for three ints like that is because:
a ^ b ^ a == b
In other words if the first and last ints contributing to the hash code are the same, they do not contribute to the final hash code at all - they cancel each other out and the result is always the middle int.
It's even worse if you are only using two ints because:
a ^ a == 0
So for two ints, for all cases where they are the same the hash code will be zero.
As you probably know the GetHashCode() is the function which should map your objects into the number such that probability of getting same number by two different objects should be as least as possible (and obviously this number should be always the same for the same object + function should be fast). From the all boolean operators (AND, OR, NOT, XOR) XOR gives best bit distribution (look at the OR, AND, XOR boolean tables). However I suggest you to check this approach: What is the best algorithm for an overridden System.Object.GetHashCode?. (hash function using prime numbers distribution property).
链接地址: http://www.djcxy.com/p/39758.html下一篇: 为什么用于计算哈希代码的xor运算符?