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.
ArrayList<String> arraylist = new ArrayList<>(); arraylist.add("one"); // ["one"] arraylist.add("two"); // ["one", "two"] arraylist.add(0, "zero"); // ["zero", "one", "two"]
1. ArrayList.add() Method
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 is an overloaded method and it allows us to supply the specified index where we want to insert the new element.
public boolean add(E e) public boolean add(int index, E e)
- Method parameter – The element ‘e’ to be appended to the end of this list. If the optional fromIndex parameter is supplied, the element is added to this index. All the subsequent elements are moved one position to the right as a result of this operation.
- Method returns –
trueif the element is added successfully.
- Method throws – no exception is thrown.
2. Examples of Adding an Element to ArrayList
For demo purposes, we have created an arraylist containing strings. We will add a spring to this list using add() method.
ArrayList<String> list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D");
2.1. Appending New Element 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
[A, B, C, D, E]
2.2. Insert New Element into Specified Index
We can add any object to the list. This is not recommended. In the following example, we are adding the string “num” to the list instance we created in the previous step.
[E, A, B, C, D]
The ArrayList class is very flexible and provides many convenient methods for adding or removing elements from it. The add() is one such method to add a new single element to the arraylist.
Although, if generics are not used, it is the programmer’s responsibility to ensure that the new element is of the same type as the other elements stored in the list.
Happy Learning !!