Capacity of an ArrayList
isn't the same as its size. Size is equal to the number of elements contained in the ArrayList
(and any other List
implementation).
The capacity is just the length of the underlying array which is used to internaly store the elements of the ArrayList
, and is always greater or equal to the size of the list.
When calling set(index, element)
on the list, the index
relates to the actual number of the list elements (=size) (which is zero in your code, therefore the AIOOBE
is thrown), not to the array length (=capacity) (which is an implementation detail specific to the ArrayList
).
The set
method is common to all List
implementations, such as LinkedList
, which isn't actually implemented by an array, but as a linked chain of entries.
Edit: You actually use the add(index, element)
method, not set(index, element)
, but the principle is the same here.