Question

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 ?

Was it helpful?

Solution

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.

OTHER TIPS

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.

With the help of Capacity of ArrayList, I could find that the capacity is not reset. Find the sample code:

import java.lang.reflect.Field;
import java.util.ArrayList;
public class Main {

    public static void main(String[] args) {
        try {
            ArrayList<Object> al = new ArrayList<Object>(500);
            System.out.println(getCapacity(al));
            for (int i = 0; i < 550; i++) {
                al.add(new Object());
            }
            System.out.println(getCapacity(al));
            al.clear();
            System.out.println(getCapacity(al));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    static int getCapacity(ArrayList<?> l) throws Exception {
        Field dataField = ArrayList.class.getDeclaredField("elementData");
        dataField.setAccessible(true);
        return ((Object[]) dataField.get(l)).length;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top