这段代码执行后 HashMap 会发生什么?
HashMap m = new HashMap();
for (int i = 0; i < 1024 * 1024; i++)
m.put(i, i);
m.clear();
1M 之后,内部哈希表将从原来的 16 增长到 1MB。clear() 是否将其调整为原始大小?
不,表格保持其大小。所有元素都设置为null
:
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
这是一个实现细节,我不知道您正在阅读什么 API,其中包含有关 1M 放置或内部哈希表的任何内容。
让我们看一个实现:
620 /**
621 * Removes all of the mappings from this map.
622 * The map will be empty after this call returns.
623 */
624 public void clear() {
625 modCount++;
626 Entry[] tab = table;
627 for (int i = 0; i < tab.length; i++)
628 tab[i] = null;
629 size = 0;
630 }
http://www.docjar.com/html/api/java/util/HashMap.java.html#621
所以 OpenJDK 7 的实现并没有恢复原来的大小。