Does HashMap.clear() resize inner hash table to the original size?

Tags: ,



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?

Answer

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;
}


Source: stackoverflow