Reputation: 6119
In Effective Java there is an example of Complex class. That class has overridden hashCode which uses hashDouble method I have a question about.
private int hashDouble(double val)
{
long longBits = Double.doubleToLongBits(re);
return (int) (longBits ^ (longBits >>> 32));
}
For what purpose it does (int) (longBits ^ (longBits >>> 32))
?
Upvotes: 2
Views: 549
Reputation: 68962
The double value is 64 bits wide but the int returned by hash method has only 32 bit. In order to achieve a better distribution of hash values (compared to simply striping the upper 32 bits).
The code uses XOR to incorporate the upper 32 bits (containing sign, exponent and some bits of the mantissa) aligned by right-shifting of the IEEE 754 value in the calculation.
Image source Wikipedia
Upvotes: 4