Search code examples
javahashhashmaphashcode

Why hash function has done XOR on hascode?


I read the explanation but I could not understand what we are achieving by doing XOR on the hashCode. Can anyone give some example.

static final int hash(Object key) {
    int h;
    return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

This code was taken from HashMap source code. I just wanted to know why they have used XOR, Marko has replied that properly that HashMap implementation uses lower-end bits. I think not only HashMap, other collections will also be doing same that is why I did not mentioned any collection name. I don't understand why people "rate down" this question.


Solution

  • This is a typical maneuver to protect from "bad" hashcodes: such whose lower-end bits are not variable enough. Java's HashMap implementation relies only on lower-end bits of the hashcode to select the bucket.

    However, this code's motivation has expired long ago because HashMap already does its own bit spreading. It would make sense if used on Hashtable, but of course no code written since year 2000 should ever use it.