The add() method inserts an element to the arraylist at the specified position.
Example
Syntax of ArrayList add()
The syntax of the add() method is:
arraylist.add(int index, E element)
Here, arraylist is an object of ArrayList class.
add() Parameters
The ArrayList add() method can take two parameters:
- index (optional) - index at which the element is inserted
- element - element to be inserted
If the index parameter is not passed, the element is appended to the end of the arraylist.
add() Return Value
- returns true if the element is successfully inserted
Note: If the index is out of the range, theadd() method raises IndexOutOfBoundsException exception.
Example 1: Inserting Element using ArrayList add()
Output
ArrayList: [2, 3, 5]
In the above example, we have created an ArrayList named primeNumbers. Here, the add() method does not have an optional index parameter. Hence, all the elements are inserted at the end of the arraylist.
Example 2: Inserting Element at the Specified Position
Output
ArrayList: [Java, Python, JavaScript] Updated ArrayList: [Java, C++, Python, JavaScript]
In the above example, we have used the add() method to insert elements to the arraylist. Notice the line,
languages.add(1, "C++");
Here, the add() method has the optional index parameter. Hence, C++ is inserted at index 1.
Note: Till now, we have only added a single element. However, we can also add multiple elements from a collection (arraylist, set, map, etc) to an arraylist using the addAll() method. To learn more, visit Java ArrayList addAll().