Knowing that to obtain hashcode for two objects it is common practice to do XOR of their respective hashcodes I wanted to check how Tuple deals with situation where Item1 == Item2
. This is what I found in the source code:
internal static int CombineHashCodes(int h1, int h2) {
return (((h1 << 5) + h1) ^ h2);
}
I assume this is to avoid having the same hashcode for all equal objects, because x ^ x = 0
. Why h1 << 5
though? Is there a reason why it's specifically 5
? Could it be just 1
? Help me understand this please.
((h1 << 5) + h1)
is equivalent to h1 * 33
and 33
is 3 * 11
.
Java uses 31
in some hashes since it's prime and h1 * 31
is (h1 << 5) - h
which is almost the same, but without additional overflows which might happen in case of sum.