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

Previously I have shown  how to add element at the end of the list in java by using add() method. There is another variant of add method which adds element at the specified index.The syntax for the method is

public void add(int index, Object element)

According to Oracle 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[]) {
        // ArrayList of String type
       ArrayList<String> al = new ArrayList<String>();
       // simple add() methods for adding elements at the end
       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("Elements after adding string San Francisco:"+ al);
       //adding string to 1st position
       al.add(0, "Texas");

       //Print
       System.out.println("Elements after adding string Texas:"+ al);
    }
}


Output

Elements after adding string San Francisco:[California, Boston, San Francisco, San jose, New York]
Elements 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