Java ArrayList length
In this article, we will take a look at the method to get the length or size of a java ArrayList with examples.
Length of an ArrayList
is the number of elements in it.
An
ArrayList
has a size()
method which returns the total number of elements present in it, at the time this method is invoked.So,
size()
method can be used to get the length of an ArrayList
.
Java docs for size()
state,
Returns the number of elements in this list
ArrayList size() example
Below is an example program which uses size()
method to get the length of an ArrayList
.
ArrayList<String> letters = new ArrayList<>(); letters.add("A"); letters.add("B"); letters.add("C"); letters.add("D"); System.out.println("Length of ArrayList is: " + letters.size()); letters.remove("B"); System.out.println("Length of ArrayList is: " + letters.size());
Output is
Length of ArrayList is: 4
Length of ArrayList is: 3
Above program adds 4 elements to the list and prints its size. Then, it removes an element and again prints its size.
Values of size are 4 and 3 respectively, which is the number of elements present in the list.
ArrayList default size
When a new ArrayList
is created, it does not have any elements and so, its length or size is 0.
As soon as first element is added, its size is increased to a default size, which is 10.
ArrayList
class contains a class or instance variable size
, which keeps track of the total number of elements in the list.Following is the implementation of
size()
method
public int size() { return size; }
When an add or remove operation is performed, size
variable is incremented or decreased accordingly.
Look at the below snippet from add()
method of ArrayList
private void add(E e, Object[] elementData, int s) { if (s == elementData.length) elementData = grow(); elementData[s] = e; size = s + 1; } }
When a new element is added, size
is increased by 1.
Similarly, below is a method which is invoked at the time of remove operation
private void fastRemove(Object[] es, int i) { modCount++; final int newSize; if ((newSize = size - 1) > i) System.arraycopy(es, i + 1, es, i, newSize - i); es[size = newSize] = null; }
Here also, size
is updated to a new value.