The add() method in Java ArrayList is used to insert elements into the list dynamically. It allows adding elements either at the end of the list or at a specific index position.
- Supports dynamic insertion of elements without needing to define the size in advance.
- Provides two forms: add(E element) and add(int index, E element).
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Creating an empty ArrayList
ArrayList<Integer> al = new ArrayList<>();
// Use add() method to
// add elements in the list
al.add(10);
al.add(20);
al.add(30);
System.out.println("" + al);
}
}
Output
[10, 20, 30]
Syntax of add(Object element)
public boolean add(Object element)
- Parameters:
element: The element to be appended to the list. - Return Type:
boolean: It returnstrue,if the element was successfully added.
Example 2: add(int index, Object element)
This method inserts the specified element at a given position in the ArrayList. It shifts the current element at that position and subsequent elements to the right.
Syntax of add(int index, Object element)
void add(int index, Object element)
Parameters:
- index: The position at which the specified element is to be inserted.
- element: The element to be inserted.
Exception: Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 or index > size()).
import java.util.*;
public class GFG {
public static void main(String[] args) {
// Creating an empty ArrayList
ArrayList<Integer> al = new ArrayList<>();
// Use add() method to
// add elements in the list
al.add(10);
al.add(20);
al.add(30);
al.add(40);
System.out.println("" + al);
// Adding new element
// at index 2
int i = 2;
al.add(i, 21);
System.out.println("" + al);
}
}
Output
[10, 20, 30, 40] [10, 20, 21, 30, 40]
Note:
- Valid Index Range: The valid range for add(index, element) is 0 ≤ index ≤ size(). If 0 ≤ index < size(), the element is inserted at that position and existing elements shift to the right; if index = size(), the element is added at the end of the list (same as add(element)).
- Invalid Index: If the index > size() or index < 0, Java throws an IndexOutOfBoundsException because elements cannot be inserted outside the valid list boundary.