EDIT: This question is not about bitwise operators and can't be answered with Why are XOR often used in java hashCode() but another bitwise operators are used rarely?
I've seen different approaches for hash calculation of object:
class A {
public B b;
public C c;
@Override
public boolean equals();
@Override
public int hashCode() {
return c.hashCode() ^ b.hashCode(); //XOR
return c.hashCode() + prime * b.hashCode(); // SUM
return Objects.hash(b,c); // LIB
}
}
It seems LIB method uses SUM, but why is it better than XOR?
Even though the example is in Java, this question is more about math and probabilities.
The SUM ensures that you use all the bits of the hashcode to spread your hashing (in this, the 32 bits of an int), and makes no assumption about sub hashcode() implementation for that.
The XOR only has the same property if the hashcode of B and C has it, else it will only use the minimum of the number of "useful" bits in B and C hashcode, which could lead to a worse distribution, and more frequent collision. It's very easy to see the problem if B and C are integers which tends to be very small, you'll only ever use the first few bits (as int.hashcode() is the identity function).
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