An ArrayList object has a capacity and a size.
- The capacity is the total number of cells.
- The size is the number of cells that have data in them.
- Cells 0 up through size-1 have data in them.
- Data are added in order. Before cell N gets data, cells 0, 1, 2, … N-1 must hold data.
The size increases by one each time an element is added. However, the capacity remains unchanged until the ArrayList is full. When an element is added to a full list, the Java runtime system will greatly increase the capacity of the list so that many more elements can be added.
Because of the above difference, 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.
// Allocating an array list of capacity 100 ArrayList list = new ArrayList <Employee>(100); // Allocating a array of size 100 Employee emp[] = new Employee[100];
If you allocate a new array with new Employee[100]
, the size of that array (arr.length) is going to be 100. It has 100 elements. All the elements are initially null (as this is an array of object references), but still, there are 100 elements.
If you do something like new ArrayList <Employee>(100)
, and try to check list.size(), you’ll get 0. There are no elements in the list.