The ArrayList.add() in Java adds a single element to the list, either at the end of the list or at the specified index position. Always use generics for compile-time type safety while adding the element to the arraylist.
1. ArrayList.add() API
The add() method first ensures that there is sufficient space in the arraylist. If the list does not have space, then it grows the list by adding more spaces in the underlying array. Then it adds the element to either the list end or a specific index position.
ArrayList add method implementation is given below.
public boolean add(E e)
public boolean add(int index, E e)
- Method parameter – The element ‘e’ to be added to this list. also an optional fromIndex parameter.
- Method returns –
true
if element is added. - Method throws – no exception is thrown.
2. ArrayList.add() Example
We have the following list instance containing alphabets. We will add another item to this list using add() method.
ArrayList<String> list = new ArrayList<>(); //list 1
list.add("A");
list.add("B");
list.add("C");
list.add("D");
2.1. Appending Item to the End of List
In the following program, we add the string “E” to the end of this list. Always use generics to ensure you add only a certain type of element to a given list.
list.add("E");
System.out.println(list1); //combined list
Program output.
[A, B, C, D, E]
2.2. Insert Item into Specified Index
We can add any object to the list. This is not recommended. In following example, we are adding the string “num” to the list instance we created in the previous step.
list.add(0, "E");
Program output.
[E, A, B, C, D]
Happy Learning !!
Read More: ArrayList Java Docs