What happens to the HashMap after this code execution?
HashMap m = new HashMap();
for (int i = 0; i < 1024 * 1024; i++)
m.put(i, i);
m.clear();
After 1M puts the inner hash table will grow from original 16 to 1MB. Does clear() resize it to the original size or not?
No. The table retains its size. All elements are set to null:
public void clear() {
modCount++;
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
tab[i] = null;
size = 0;
}
This is an implementation detail, and I don't know what API you're reading that says anything about 1M puts or an inner hash table.
Let's just look at an implementation:
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
So the OpenJDK 7 implementation does not restore the original size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With