English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The Java ArrayList add() method inserts an element at the specified position in the ArrayList.
Syntax of add() method:
arraylist.add(int index, E element)
The ArrayList add() method can take two parameters:
index (Optional)- Index of the element to be inserted
element - Element to be inserted
If no index is passed, the element is appended to the end of the arraylist.
If the element is successfully inserted, it returns true.
Note:If the index is out of range, the add() method throws an IndexOutOfBoundsException exception.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create ArrayList ArrayListprimeNumbers = new ArrayList<>(); //Insert element into the arraylist primeNumbers.add(2); primeNumbers.add(3); primeNumbers.add(5); System.out.println("ArrayList: " + primeNumbers); } }
Output Result
ArrayList: [2, 3, 5]
In the above example, we created an ArrayList named primeNumbers. Here, the add() method does not have an optional index parameter. Therefore, all elements are inserted at the end of the arraylist.
import java.util.ArrayList; class Main { public static void main(String[] args) { //Create ArrayList ArrayListlanguages = new ArrayList<>(); // Insert element at the end of the arraylist languages.add("Java"); languages.add("Python"); languages.add("JavaScript"); System.out.println("ArrayList: " + languages); // at Position1Insert Element languages.add(1, "C++"); System.out.println("Updated ArrayList: ", + languages); } }
Output Result
ArrayList: [Java, Python, JavaScript] Updated ArrayList: [Java, C++, Python, JavaScript]
In the above example, we use the add() method to insert elements into the arraylist. Note this line,
languages.add(1, "C++");
Here, the add() method has an optional index parameter. Therefore, C++at index1insertion.
NoteAs of now, we have only added a single element. However, we can also use the addAll() method to add multiple elements from a collection (array list, set, map, etc.) to an array list. For more information, please visitJava ArrayList addAll().