为什么HashMap的方法hash(int h)是这样的?

时间:2013-07-22 04:43:17

标签: java hashmap

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);
}

有人能告诉我为什么这个哈希方法设计得像这样?有什么好处?

1 个答案:

答案 0 :(得分:3)

如果看到Open JDK Source

此方法有评论......

/**
          * 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.
 */