It is necessary to clarify two definitions:
The size represent the number of elements in the list.
The capacity represent the length of the internal array. In other words, the length contains the number of places to put an element;
list size = 2
When you create one list with the default constructor of Arraylist:
Ex:
List<String> list = new ArrayList<>();
System.out.println(l.size());
The output is : 0
Why?
Because the list is empty, this is explained by the internal array of the list, when you use the default constructor of ArrayList, the internal array is :
private static final Object[] EMPTY_ELEMENTDATA = {};
So, an empty array of Objects where the value of the length is 0 (Capacity). As the list is empty the size is 0.
(id of elementData=27)
When you add one element to the list, the size of your list is incremented to 1, and the initial internal array of your list is changed by another array with a length of 10 (capacity); (id of elementData=30)
private static final int DEFAULT_CAPACITY = 10
(id of elementData=30)
About the default constructor of ArrayList, the API java says :
API Java : https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#ArrayList%28%29
public ArrayList()
Constructs an empty list with an initial capacity of ten.
In other words, this constructor create an empty list (size equals to 0) with an initial capacity of ten elements.(After add one element to the list, the capacity of the list become 10)
When you know the size of your list, you should create your list with this size. Why? because the complexity of the method add (E element)
is O(1) amortized (when there is available space in your list), but O(n) (worst-case) if you add more elements than the initial capacity of your list, in this case, a new array (1.5 times the size) is allocated, and the old array is copied to the new one. Clearly, this operation has costs in terms of performance and memory resources.
So, create a list with an initial capacity of 0 has no sense. If you don't know the initial capacity of your list, use the default constructor that give to you one list with an initial capacity of ten elements.
Keep in mind that definitions of size and capacity around ArrayList are differents:
From book Core Java 2: Fundamentals
Allocating an array list as new ArrayList <'Employee>(100) //
capacity is 100
is not the same as allocating a new array as new Employee[100] // size is 100
There is an important distinction between the capacity of an array list and the size of an array. If you allocate an array with 100
entries, then the array has 100 slots, ready for use. An array list
with a capacity of 100 elements has the potential of holding 100
elements (and, in fact, more than 100, at the cost of additional
reallocations); but at the beginning, even after its initial
construction, an array list holds no elements at all.