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.
boolean.
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
        fruits.add("Banana");
        fruits.add("Apple");
        fruits.add("mango");
        fruits.add("orange");
        System.out.println(fruits);
    }
}
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
      arrlist.add(15);
      arrlist.add(22);
      arrlist.add(30);
      arrlist.add(40);

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

Output:

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

Comments