为什么HashMap 16的初始容量(2的幂)和Hashtable 11的初始容量(素数)? [英] Why is the initial capacity in HashMap 16 (power of two) and the initial capacity of Hashtable 11(prime number)?

查看:186
本文介绍了为什么HashMap 16的初始容量(2的幂)和Hashtable 11的初始容量(素数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请说明原因。我用Google搜索了它,但是找不到很好解释的答案。

Please describe the reason if you know. I Googled it, but didn't find well explained answers.

当您的 hashCode 是否为负?

推荐答案

对于 HashMap ,索引中的存储Map条目的数组是通过这种方式计算的(其中 h 是根据键的 hashCode 计算的) :

For HashMap, the index in the array that stores the entries of the Map is calculated this way (where h is calculated from the hashCode of the key):

static int indexFor(int h, int length) {
    return h & (length-1);
}

长度 数组的长度。

仅当 length 为2的幂时,此函数才有效。 c> length 不是2的幂,则必须将此代码更改为效率较低的 return h%length

This only works when length is a power of 2. If length wasn't power of 2, you would have to change this code to the less efficient return h % length.

这篇关于为什么HashMap 16的初始容量(2的幂)和Hashtable 11的初始容量(素数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆