Does HashMap.clear () resize the original size?

What happens to the HashMap after executing this code?

HashMap m  = new HashMap();
for (int i = 0; i < 1024 * 1024; i++)
    m.put(i, i);
m.clear();

      

After 1M puts in the internal hash table, it will grow from the original 16 to 1 MB. Is clear () resizing to its original size or not?

+3


source to share


2 answers


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

      

+4


source


This is an implementation detail, and I don't know which API you are reading that says anything about 1M puts or the internal hash table.

Let's take a look at the 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

Thus, the OpenJDK 7 implementation does not restore its original size.

+2


source







All Articles