Skip to content
Advertisement

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

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?

Advertisement

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;
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement