ArrayList add(int index, E element) method in java

Let’s learn ArrayList add(int index, E element) method in java.

ArrayList add(int index, E element) method in java

add(int index, E element) method of ArrayList class inserts the specified element at the specified position in this list.

Parameters:

index index at which the specified element is to be inserted.

element element to be inserted.

Throws:

IndexOutOfBoundsException – if the index is out of range(index < 0 || index > size()).

Also read – ArrayList in java

Now let’s see example on add(int index, E element) method.

import java.util.ArrayList;
public class ArrayListAddMethodExample
{
   public static void main(String[] args)
   {
      // creating an empty ArrayList with initial capacity
      ArrayList<Integer> al = new ArrayList<Integer>(6);
      al.add(12);
      al.add(14);
      al.add(16);
      al.add(18);
      al.add(20);
      // adding element 15 at fourth position
      al.add(3, 15);
      for(Integer number : al)
      {
         System.out.println("Number: " + number);
      }
   }
}


Output:

Number: 12
Number: 14
Number: 16
Number: 15
Number: 18
Number: 20