Junior — Middle
How is the initial size of an ArrayList determined when it is created?
sobes.tech AI
Answer from AI
In Android (Java), when creating an ArrayList object without specifying an initial size, the internal array is initialized with a default capacity.
-
If you call the constructor
new ArrayList<>(), the internal array is initially empty (in fact, an empty array), and the first time an element is added, an array with a capacity of 10 is allocated. -
If you call the constructor with a parameter
new ArrayList<>(initialCapacity), the internal array is immediately created with the specified capacity.
Thus, the default initial size of the internal array is 10, but it is actually allocated upon the first addition of an element.
Example:
ArrayList<String> list = new ArrayList<>(); // capacity 0, upon first add() an array of 10 elements is allocated
ArrayList<String> listWithCapacity = new ArrayList<>(20); // capacity 20 immediately