【问题标题】:Why does the method hash(int h) of HashMap like this? [duplicate]为什么HashMap的方法hash(int h)会这样呢? [复制]
【发布时间】:2013-07-22 04:43:17
【问题描述】:
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);
}

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

【问题讨论】:

  • 这段代码来自哪里?输入值是多少?
  • 是java的HashMap的方法。输入值是对象的哈希码
  • 所以它是散列一个散列?我不认为这是有道理的......
  • @Brad 除非你不相信你得到的哈希值。看看 Integer.hashCode() 并考虑一个小地图它只需要低 4 位。
  • 顺便说一句,您可以将此扩展到其他机器人大小。第一行将位划分为 3 个稍微不等的部分,第二行将此范围划分为 3。这意味着一个位可以切换 9 位结果。

标签: java hashmap


【解决方案1】:

如果你看到Open JDK Source

这个方法有 cmets...

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

【讨论】:

  • +1 这样做是因为一些 hashCode 函数非常简单。例如 Integer.hashCode 或 Inet4Addess.hashCode() 由于 HashMap 的大小是 2 的幂,它只占用低位。这意味着所有具有相同低位的密钥都会发生冲突,这对于 IP 地址来说很容易做到。
猜你喜欢
  • 1970-01-01
  • 2011-01-25
  • 2019-05-20
  • 2016-07-12
  • 2012-11-07
  • 1970-01-01
  • 2012-07-08
  • 1970-01-01
相关资源
最近更新 更多