Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hashmap

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?

like image 703
Evgeniy Dorofeev Avatar asked Dec 13 '25 05:12

Evgeniy Dorofeev


2 Answers

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;
}
like image 67
Bozho Avatar answered Dec 14 '25 20:12

Bozho


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.

like image 39
Matt Ball Avatar answered Dec 14 '25 18:12

Matt Ball