Sobes.tech
Senior

How to implement hashCode() for a Long type (64 bits) to return an int (32 bits)?

sobes.tech AI

Answer from AI

To implement the hashCode() method for the Long type (64 bits), which returns an int (32 bits), it is common to use the XOR operation between the upper and lower 32 bits of the value. This allows for a uniform distribution of bits and results in a 32-bit hash.

Example implementation in Java:

@Override
public int hashCode() {
    long value = this.longValue; // original 64-bit value
    return (int)(value ^ (value >>> 32));
}

Here, value >>> 32 shifts the number 32 bits to the right without sign, extracting the upper half, and XOR combines it with the lower half, giving the final 32-bit hash.