java - 当 HashMap 增加其大小时,HashMap 中值的索引会发生什么变化?

标签 java dictionary hash hashmap hashtable

我理解当我们声明如下 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/

相关文章:

python - 如何在字典中存储 tkinter 按钮小部件?

python - 如何使用递归遍历多个列表

javascript - 如何使用 Node.js 的加密库生成 scrypt 哈希?

java - Linux 命令行 SHA-256 哈希与在线工具不同?

php - 哈希密码 php

java - PaintComponent 方法仅被调用一次

java - tcp 发送接受了错误的字节

java - Files.copy 抛出 java.nio.file.NoSuchFileException 即使要复制的文件确实存在

java - 使用正则表达式从字符串中提取姓名和电子邮件地址

c# - 错误 : Not all code paths return a value