How does ArrayList work?
Internally an ArrayList
uses an Object[]
.
As you add items to an ArrayList
, the list checks to see if the backing array has room left. If there is room, the new item is just added at the next empty space. If there is not room, a new, larger, array is created, and the old array is copied into the new one.
Now, there is more room left, and the new element is added in the next empty space.
Since people really like the source code:
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer.
*/
private transient Object[] elementData;
Straight out of the JDK.
It uses an Object[]
, and makes a bigger array when the array gets full.
You can read the source code here.
ArrayList uses an Array of Object to store the data internally.
When you initialize an ArrayList, an array of size 10 (default capacity) is created and an element added to the ArrayList is actually added to this array. 10 is the default size and it can be passed as a parameter while initializing the ArrayList.
When adding a new element, if the array is full, then a new array of 50% more the initial size is created and the last array is copied to this new array so that now there are empty spaces for the new element to be added.
Since the underlying data-structure used is an array, it is fairly easy to add a new element to the ArrayList as it is added to the end of the list. When an element is to be added anywhere else, say the beginning, then all the elements shall have to move one position to the right to create an empty space at the beginning for the new element to be added. This process is time-consuming (linear-time). But the Advantage of ArrayList is that retrieving an element at any position is very fast (constant-time), as underlying it is simply using an array of objects.