Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Clearing an ArrayList preserve its Capacity

As the title mentions, if I create an ArrayList with initial capacity 500 and then clear it after some time will its capacity still be 500 ? or do I need to re-init it for that ?

like image 675
Cemre Mengü Avatar asked Feb 19 '23 08:02

Cemre Mengü


2 Answers

Yes, it preserves its capacity. (at least, not in the implementation of the Oracle VM):

/**
 * Removes all of the elements from this list.  The list will
 * be empty after this call returns.
 */
public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

Just to be clear: an ArrayList is backed by an array (e.g. int[] for ArrayList) and that array is expanded whenever you go over capacity by creating a new array and copying things over. Clearing will not (as seen in the code) create a new smaller array, copy things there, and destroy the old big array.

like image 147
Miquel Avatar answered Feb 28 '23 11:02

Miquel


No, arrayList's capacity is not changed if you remove the elements from the list. But you can do that yourself using trimToSize.

In general, you don't need to worry about the capacity as it's increased as you add more elements. The possible reason to worry about capacity is performance due to frequent re-allocation. Otherwise, you don't need to worry about re-initializing the capacity.

like image 21
P.P Avatar answered Feb 28 '23 11:02

P.P