一文读懂HashMap和HashTable的区别以及常见面试题( 七 )

\n

2、 在看(1)、(2)处 。 这里是HashMap的精华所在 。 首先是hash方法 , 该方法为一个纯粹的数学计算 , 就是计算h的hash值 。

\n

static int hash(int h) {
       h ^= (h >>> 20) ^ (h >>> 12);        return h ^ (h >>> 7) ^ (h >>> 4);
   

\n

我们知道对于HashMap的table而言 , 数据分布需要均匀(最好每项都只有一个元素 , 这样就可以直接找到) , 不能太紧也不能太松 , 太紧会导致查询速度慢 , 太松则浪费空间 。 计算hash值后 , 怎么才能保证table元素分布均与呢?我们会想到取模 , 但是由于取模的消耗较大 , HashMap是这样处理的:调用indexFor方法 。

\n

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

\n

HashMap的底层数组长度总是2的n次方 , 在构造函数中存在:capacity <<= 1;这样做总是能够保证HashMap的底层数组长度为2的n次方 。 当length为2的n次方时 , h&(length - 1)就相当于对length取模 , 而且速度比直接取模快得多 , 这是HashMap在速度上的一个优化 。 至于为什么是2的n次方下面解释 。

推荐阅读