Java ArrayList add() Method Example

ArrayList Methods with Examples


Java ArrayList Examples


The java.util.ArrayList.add(E e) method appends the specified element E to the end of the list.

ArrayList add() method is used to add an element in 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.

Java ArrayList add() Method Example

The following example shows the usage of java.util.ArrayList.add(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 specific position

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);
      }  
   }
}   
Let us compile and run the above program, this will produce the following result −
Number = 15
Number = 22
Number = 25
Number = 30
Number = 40

Comments