Pergunta

Here is a method from a HashMap implementation from java.util package:

static int secondaryHash(Object key) {
    int hash = key.hashCode();
    hash ^= (hash >>> 20) ^ (hash >>> 12);
    hash ^= (hash >>> 7) ^ (hash >>> 4);
    return hash;
}

Can somebody explain what are these ^=, >>>, ^ things are and what's going on here?

Foi útil?

Solução

x ^= y : is the short hand operator for x = x ^ y.

^ : is the binary exclusive-or operator XOR.

y >>> x : is the binary shift operator which shifts all bits of y x-bits to the right while filling in 0-bits to the left. This means the sign will not be preserved if the initial value was a negative number.

Outras dicas

The ^ operator performs a bitwise XOR of two integer quantities.

The ^= is similar to += except for ^.

The operator >>> is a logical right shift, which moves each bit towards the right, removing those bits that fall off the right. On the left 0's are filled in.

static int secondaryHash(Object key) {
    int hash = key.hashCode();
    hash ^= (hash >>> 20) ^ (hash >>> 12); // Set hash to equal to bitwise XOR of it with itself right shifted by 20 and right shifted by 12.
    hash ^= (hash >>> 7) ^ (hash >>> 4);   // Same thing for right shift by 7 and right shift by 4.
    return hash;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top