ArrayList add Method

In this tutorial, we will learn how to use the important Java ArrayList class add() method with an example.

ArrayList add Method Overview

ArrayList provides two overloaded add() methods.

1. void add(int index, E element) - Inserts the specified element at the specified position in this list.
2. add(E e) - Appends the specified element to the end of this list.

The ArrayList add() method is used to add an element to the list. We can add elements of any type in ArrayList, but make the program behave in a more predictable manner, we should add elements of one certain type only in any given list instance.

ArrayList add Method Example

The following example shows the usage of java.util.ArrayList.add(i, E) method:
import java.util.ArrayList;
import java.util.List;

// How to create an ArrayList using the ArrayList() constructor.
// Add new elements to an ArrayList using the add() method.
public class CreateArrayListExample {

    public static void main(String[] args) {
        // Creating an ArrayList of String using
        List<String> fruits = new ArrayList<>();
        // Adding new elements to the ArrayList
Let us compile and run the above program, this will produce the following result −
[Banana, Apple, mango, orange]

Java ArrayList add() Method Example - Insert element in a specific position

The following example shows the usage of java.util.ArrayList.add(E) method:
import java.util.ArrayList;

public class ArrayListDemo {
   public static void main(String[] args) {

      // create an empty array list with an initial capacity
      ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

      // use add() method to add elements in the list

      // adding element 25 at third position
      // let us print all the elements available in list
      for (Integer number : arrlist) {
         System.out.println("Number = " + number);


Number = 15
Number = 22
Number = 25
Number = 30
Number = 40