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

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

谁能告诉我,为什么这个哈希方法要这样设计?有什么好处?

最佳答案

如果您看到 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.
 */

关于java - 为什么HashMap的方法hash(int h)是这样的呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17780090/

相关文章:

java - 无限跨9.1 : Unsupported async cache mode 'REPL_ASYNC' for transactional caches

hadoop - 在Hadoop中合并两个SortedMapWritable?

java - 将 HashMap 用于节点和图数据结构

java - 如何执行 CompletableFuture 数组并组合它们的结果

java - 无法使用java客户端7.0通过appium滚动android native 应用程序

java - Ganymed vs JSch?

java - 在 java 的 HashMap 中使用 char[] 数组

java - 更新 JHipster 生成器后如何更新 JHipster 项目?

java - 将对象转换为 HashMap

java - 如何从员工列表中打印特定月份加入的员工列表?