W3docs

Initial size for the ArrayList

The initial size of an ArrayList in Java is 0.

The initial size of an ArrayList in Java is 0. It is important to distinguish between size (the number of elements currently in the list) and capacity (the internal array size). The ArrayList class is a resizable array implementation of the List interface, which means that the size of the ArrayList can grow or shrink as needed to accommodate the elements added to or removed from the list.

Prior to Java 9, the ArrayList class created an empty list with an initial capacity of 10. This means that the ArrayList will automatically resize itself when you add the eleventh element to the list, and it will allocate a new array with a capacity of 15 (1.5x growth) to store the elements. Since Java 9, the default capacity of 10 is lazily initialized only when the first element is added, avoiding unnecessary memory allocation for empty lists.

You can specify a different initial capacity for the ArrayList when you create it, using the ArrayList(int initialCapacity) constructor.

import java.util.ArrayList;
import java.util.List;

List<String> list = new ArrayList<>(20);

This will create an ArrayList with an initial capacity of 20. The ArrayList will still resize itself as needed when you add more elements to the list, but it will not need to do so as often as it would with the default initial capacity of 10.

Keep in mind that specifying a larger initial capacity will increase the amount of memory used by the ArrayList, but it can improve the performance of the ArrayList if you know that you will be adding a large number of elements to the list.

I hope this helps! Let me know if you have any other questions.