相关疑难解决方法(0)

理解奇怪的Java哈希函数

以下是哈希函数的源代码java.util.HashMap.评论很好地解释了它的成就.但怎么样?什么是^>>>运营商在做什么?有人可以解释代码实际上如何评论所说的内容吗?

/**
 * 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.
 */
static int hash(int h) {
    // This function ensures …
Run Code Online (Sandbox Code Playgroud)

java hash

33
推荐指数
3
解决办法
7243
查看次数

为什么HashMap会重新生成密钥对象提供的哈希码?

我正在阅读Java 1.6 API提供的HashMap类的代码,无法完全理解以下操作的需要(在put和get方法的主体中找到):

int hash = hash(key.hashCode());
Run Code Online (Sandbox Code Playgroud)

方法hash()具有以下主体:

 private static int hash(int h) {
         h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}
Run Code Online (Sandbox Code Playgroud)

这通过对提供的哈希码执行位操作来有效地重新计算哈希值.即使API声明如下,我也无法理解这样做的必要性:

这很关键,因为HashMap使用两个幂的长度哈希表,否则会遇到低位不同的hashCodes的冲突.

我确实理解键值是存储在数据结构数组中的,并且该数组中项的索引位置由其哈希确定.我无法理解的是这个函数如何为哈希分布添加任何值.

java collections hash hashmap hashcode

17
推荐指数
1
解决办法
5719
查看次数

标签 统计

hash ×2

java ×2

collections ×1

hashcode ×1

hashmap ×1