哈希表的负载系数和容量

use*_*194 3 java hash

当散列表中的条目数超过负载因子和当前容量的乘积时,容量如何增加?

sti*_*vlo 5

这取决于底层实现.例如,在HashMap中,底层存储是一个数组:

transient Entry[] table;
Run Code Online (Sandbox Code Playgroud)

Entry对象包含键和值.当容量不足时(正如您所说的那样,超出了负载系数和当前容量的乘积),将创建一个新数组并将旧值复制到其中.

查看HashMap for OpenJdk 7 的源代码并查找void resize(int newCapacity).该方法中最重要的一行是:

Entry[] newTable = new Entry[newCapacity];   //create the new table
transfer(newTable);                          //transfer and rehash the data
table = newTable;                            //from now on use the new table
threshold = (int)(newCapacity * loadFactor); //compute the new threshold
Run Code Online (Sandbox Code Playgroud)

threshold是在再次增大大小之前可以包含的最大元素数.transfer()还重新元素,因此元素可能存储在不同的数组索引中,与原始位置相比.您可以查看代码,阅读起来非常简单.