Last Updated : 10 Dec, 2024
The add() method in the ArrayList class is used to add elements to the list. There are different versions of this method.
Example 1: In this example, we will use the add() method to add elements at the end of the list.
Java
// Java Program to demonstrate Addition of
// Elements to an ArrayList
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);
}
}
Syntax of add(Object element)
public boolean add(Object element)
element
: The element to be appended to the list.boolean
: It returns true,
if the element was successfully added.There are two versions of the ArrayList add() method i.e. one without specifying an index and another with a specified index.
The above example and syntax is without specifying an index, now let's see the implementation of the second version below:
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:
Exception: Throws IndexOutOfBoundsException if the specified index is out of range (index < 0 or index > size()).
Example:
Java
// Java Program to demonstrate
// Addition of elements at a specified index
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);
}
}
[10, 20, 30, 40] [10, 20, 21, 30, 40]
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4