How to add element at specified index in ArrayList : add(int index, E element) example

I have already shared  how to add element at the end of the list in java by using add() method. There is another variant of add(index, element) which adds element at the specified index.

The syntax for the method is

public void add(int index, Object element)

According to Java docs, It inserts the specified element at the specified position in the ArrayList.

add(int index, Object element) Example

import java.util.*;
public class AddMethodExample {
    public static void main(String args[]) { 
 
       // Declaration of String ArrayList
       ArrayList<String> al = new ArrayList<String>(); 
 
       /* Simple add() method for adding element
          at the end of the ArrayList */ 
       al.add("California");
       al.add("Boston");
       al.add("San jose");
       al.add("New York");
 
       //Adding element to the 3rd position
       //3rd position = 2 index as index starts with 0
       al.add(2,"San Francisco");
       System.out.println("ArrayList after adding String San Francisco:"+ al);
        
       //Addition of String element at 1st position
       al.add(0, "Texas");

       //Displaying the ArrayList
       System.out.println("ArrayList after adding String Texas:"+ al);
    }
}


Output

ArrayList after adding String San Francisco:[California, Boston, San Francisco, San jose, New York]
ArrayList after adding String Texas:[Texas, California, Boston, San Francisco, San jose, New York] 

About The Author

Subham Mittal has worked in Oracle for 3 years .
For more java articles ,Click here to Subscribe JavaHungry