I
I
Igor2018-12-20 15:22:22
Java
Igor, 2018-12-20 15:22:22

I'm looking at Java sources: HashMap bucket implementation - why is HashCode "hashed" again?

I looked at the implementation of HashMap in the Java sources and this is what I saw:

private static int hash(Object x, int length) {
        int h = System.identityHashCode(x);
        // Multiply by -127, and left-shift to use least bit as part of hash
        return ((h << 1) - (h << 8)) & (length - 1);
    }

Question about the last line.
As you can see, to get the index of the desired bucket, the hash code discards the high bits using logical AND. But what is shift manipulation?
1. How to mathematically prove that this is better than just discarding bits (without these manipulations)?
2. This transformation could make sense to increase the contribution of the high bits of the hashcode, but this does not happen here. Or I'm wrong?
3. And another oddity - System.identityHashCode(x) is its de facto address in memory. It turns out that HashMap does not use the overridden HashCode of the child? Or am I looking at the wrong piece of code?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question