What's meant by parameter (int initial capacity) in an arraylist
It's the initial capacity, i.e. the number of items that ArrayList
will allocate to begin with as the internal storage of items.
ArrayList
can contain "any number of items" (as long you have the memory for it) and when doing large initial insertions you can tell ArrayList
to allocate a larger storage to begin with as to not waste CPU cycles when it tries to allocate more space for the next item.
Example:
ArrayList list = new ArrayList<Integer>(2);
list.add(1); // size() == 1
list.add(2); // size() == 2, list is "filled"
list.add(3); // size() == 3, list is expanded to make room for the third element
Practically speaking, it's how many elements you can add to the ArrayList
before it resizes in the background, which can save you some cycles if used correctly.
Capacity is the size of the internal storage of the objects. The internal storage is always greater than or equal to the size() of the list (so that it can contain all elements).
public class Main {
public static void main(String[] args) throws Exception {
ArrayList<Integer> arr = new ArrayList<>();
System.out.println("initial size = " + arr.size()); // 0
System.out.println("initial capacity = " + getCapacity(arr));
for (int i = 0; i < 11; i++)
arr.add(i);
System.out.println("size = " + arr.size()); // 11
System.out.println("capacity = " + getCapacity(arr));
}
static int getCapacity(ArrayList<?> l) throws Exception {
Field dataField = ArrayList.class.getDeclaredField("elementData");
dataField.setAccessible(true);
return ((Object[]) dataField.get(l)).length;
}
}
Running this gives:
initial size = 0
initial capacity = 10
size = 11
capacity = 16