Java ArrayList add() Method
The add() method inserts an element into the specified position of a dynamic array.
The syntax for the add() method is:
arraylist.add(int index, E element)
Note: arraylist is an object of the ArrayList class.
Parameter Description:
- index (optional parameter) - represents the index at which the element is to be inserted
- element - the element to be inserted
If the index is not provided, the element will be appended to the end of the array.
Return Value
Returns true if the element is successfully inserted.
Note: If the index is out of range, the add() method throws an IndexOutOfBoundsException.
Example
Inserting elements using the ArrayList add() method:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create an array
ArrayList<Integer> primeNumbers = new ArrayList<>();
// Insert elements into the array
primeNumbers.add(2);
primeNumbers.add(3);
primeNumbers.add(5);
System.out.println("ArrayList: " + primeNumbers);
}
}
Executing the above program outputs:
ArrayList: [2, 3, 5]
In the above example, we created an array named primeNumbers. The add() method here does not include the optional parameter index. Therefore, all elements are inserted at the end of the array.
Inserting elements at a specified position:
Example
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Create an array
ArrayList<String> sites = new ArrayList<>();
// Insert elements at the end of the array
sites.add("Google");
sites.add("tutorialpro");
sites.add("Taobao");
System.out.println("ArrayList: " + sites);
// Insert an element at the first position
sites.add(1, "Weibo");
System.out.println("Updated ArrayList: " + sites);
}
}
Executing the above program outputs:
ArrayList: [Google, tutorialpro, Taobao]
Updated ArrayList: [Google, Weibo, tutorialpro, Taobao]
In the above example, we used the add() method to insert elements into the array.
Note this line:
sites.add(1, "Weibo");
We know that the index parameter in the add() method is optional. So, "Weibo" is inserted at the index position 1.
Note: So far, we have only added a single element. However, we can also use the addAll() method to add multiple elements from a collection (arraylist, set, map, etc.) to an array. For more information, visit Java ArrayList addAll().