HaspMap中的那个hash函数是干啥用的?

dreamhunter_lan dreamhunter_lan 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
在HashMap中,在get和put(可能还有其他地方,没记那么多)的时候都对key的hashCode进行hash,返回一个hash然后进行添加或者get。具体是这样的:
int hash = hash(key.hashCode());

然后hash函数的实现是这样:

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

我把注释也贴出来了,因为就是看不懂注释,那些注释具体的是啥,英语实在太烂了。能举个例子说说最好了。
...全文
评论 10
收藏 已收藏
分享
返回顶部
dreamhunter_lan
Java SE 62,620 成员 307,251 内容