Join our newsletter for the latest updates.

Java ArrayList add()

The Java ArrayList add() method inserts an element to the arraylist at the specified position.

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()

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<Integer> primeNumbers = new ArrayList<>();

        // insert element to the arraylist
        primeNumbers.add(2);
        primeNumbers.add(3);
        primeNumbers.add(5);

        System.out.println("ArrayList: " + primeNumbers);
    }
}

Output

ArrayList: [2, 3, 5]

In the above example, we have created an ArrayList named primeNumbers. Here, the add() method does not have optional index parameter. Hence, all the elements are inserted at the end of the arraylist.


Example 2: Inserting Element at the Specified Position

import java.util.ArrayList;

class Main {
    public static void main(String[] args) {
        // create an ArrayList
        ArrayList<String> languages = new ArrayList<>();

        // insert element at the end of arraylist
        languages.add("Java");
        languages.add("Python");
        languages.add("JavaScript");
        System.out.println("ArrayList: " + languages);

        // insert element at position 1
        languages.add(1, "C++");
        System.out.println("Updated ArrayList: " + languages);
    }
}

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 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().