我理解当我们声明如下 map 时:
Map <String, Integer> map = new HashMap ();
默认加载因子为0.75,大小为16,当map的buckets超过12个元素时,大小变为32。
但是,当使用 put 函数时, map 选择将放置对象的桶的索引的方式由 hascode % n
定义,但是本地图大小超过时会发生什么负载系数? n 不再具有相同的值,因此,如果在应用 hascode % n
时,结果索引将与之前不同,您如何找到之前设置的条目?
我的最后一个问题是:
我们增加大小后,桶的索引如何保持相同?
最佳答案
简单的答案是不能。 HashMap
必须在扩展时对所有元素执行重新散列。
参见下面的方法:
/**
* Transfers all entries from current table to newTable.
*/
void transfer(Entry[] newTable, boolean rehash) {
由 resize
调用。 JavaDoc 说
Rehashes the contents of this map into a new array with a larger capacity. This method is called automatically when the number of keys in this map reaches its threshold.
强调我的
另见:
关于java - 当 HashMap 增加其大小时,HashMap 中值的索引会发生什么变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53003761/