How does Java 8's HashMap degenerate to balanced trees when many keys have the same hash code?

前端 未结 3 467
礼貌的吻别
礼貌的吻别 2020-12-01 07:57

How does Java 8\'s HashMap degenerate to balanced trees when many keys have the same hash code? I read that keys should implement Comparable to define an order

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 08:45

    HashMap has it's own hash method that applies a supplemental 2 bit lenght hash to the objects inside in order to avoid this problems:

    Applies a supplemental hash function to a given hashCode, which defends against poor quality hash functions. This is critical because HashMap uses power-of-two length hash tables, that otherwise encounter collisions for hashCodes that do not differ in lower bits. Note: Null keys always map to hash 0, thus index 0.

    If you want to see how it's done, take a look is inside the source of the HashMap class.

    static int hash(int h) {
        // This function ensures that hashCodes that differ only by
        // constant multiples at each bit position have a bounded
        // number of collisions (approximately 8 at default load factor).
        h ^= (h >>> 20) ^ (h >>> 12);
        return h ^ (h >>> 7) ^ (h >>> 4);
    }
    

提交回复
热议问题