Java doc says - 当哈希表中的条目数超过加载因子和当前容量的乘积时,哈希表将重新哈希
在以下程序中 -
HashMap<Integer, String> map = new HashMap<Integer, String>();
int i = 1;
while(i<16) {
map.put(i, new Integer(i).toString());
i++;
}
键类型为 Integer ,插入第13到第15个元素时HashMap容量保持为16,阈值保持为12,为什么?
在地图中添加第13个元素后调试屏幕截图 -
args String[0] (id=16)
map HashMap<K,V> (id=19)
entrySet null
hashSeed 0
KeySet null
loadFactor 0.75
modCount 13
size 13
table HashMap$Entry<K,V>[16] (id=25)
threshold 12
values null
i 14
[null, 1=1, 2=2, 3=3, 4=4, 5=5, 6=6, 7=7, 8=8, 9=9, 10=10, 11=11, 12=12, 13=13, null, null]
类型为String的键的HashMap - HashMap<String, String>
或自定义类 - Map<Employee,Integer>
显示第13次插入时的预期行为
答案 0 :(得分:5)
看起来这种行为是由于最新版本的Java 7中HashMap PUT方法的内部实现发生了变化。经过多个版本的源代码后,找到了我的问题的答案
HashMap put方法调用addEntry()来添加新条目 -
public V put(K key, V value) {
...
int hash = hash(key);
int i = indexFor(hash, table.length);
...
addEntry(hash, key, value, i);
...
}
jdk7-b147 HashMap.addEntry方法看起来像 -
addEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
if (size++ >= threshold)
resize(2 * table.length);
}
版本1.7.0_67-b01的源代码如下 -
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
因此,在Java的最新版本中,可能不会仅基于阈值来调整HashMap的大小。如果存储桶为空,则无需调整HashMap的大小就可以进入
Java 8可能有不同的行为,source code of version 8-b132显示PUT完全重新实现 -
put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
....
}
final Node<K,V>[] resize() {
//many levels of checks before resizing
}
Java doc可能不像Java版本那样频繁更新!谢谢史蒂芬