在 HashMap 实现中调整数组 table 的大小

Resizing of array table in HashMap implementation

这是一个简单的问题,适合了解 HashMap 内部实现的人:)

初始大小为 16 个桶,负载因子为 0.75。意思是当它 得到 (注意那个词)12 时,它会调整到 32 个桶。

我的问题是,当它获得 12 个键值对时或当它获得 12 'filled' 个桶时,它是否将大小从 16 个桶调整为 32 个桶?我问这个是因为这 16 个桶中的所有 12 个键值对都可能被插入到同一个桶中。在那种情况下,调整大小会很奇怪,因为其他 15 个完全是空的。

谢谢,如有任何意见,我们将不胜感激:)

来自 JavaDoc https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-K-V-

When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

因此,当 HashMap 有 12 key-value 对时,它会调整大小。这并不奇怪,因为调整条目大小后它们的存储桶会发生变化。

this link所述。

It represents that 12th key-value pair of hashmap will keep its size to 16. As soon as 13th element (key-value pair) will come into the Hashmap, it will increase its size from default 2^4 = 16 buckets to 2^5 = 32 buckets.

独立于每个键插入的位置,当负载因子和当前容量的乘积超过时,table将调整大小。

在达到负载因子之前,HashMap 不关心使用了多少个桶,它知道发生冲突的概率变得太大,应该调整映射的大小。尽管已经发生了很多碰撞。