Add element to specified index of Java ArrayList example

In this example we will learn how to add an element to a specified index of an Java ArrayList. To add an element to the specified in index of the arraylist, we will follow the below steps.

  • First step is that we need to create a new ArrayList.
  • Populate the arrayList with elements, using add(E e) API method of ArrayList.
  • Use add(int index, E element) method of the ArrayList.
  • The method inserts the specified the element at the specified position in this list, without overwriting the element previously at the specified index, instead shifts the existing element to the right.

import java.util.ArrayList;

public class AddAtIndexExample 
{
    public static void main(String[] args) {
        // Create ArrayList of String type
        ArrayList<String> arrayList1 = new ArrayList<String>();
        // simple add() methods for adding elements at the end
        arrayList1.add("element1");
        arrayList1.add("element2");
        arrayList1.add("element3");
        //Print the elements of the ArrayList
        System.out.println("**Elements of arrayList1 before add**");
        for(String val : arrayList1)
        {
            System.out.println(val);
        }
        //adding element to the 2nd position
        arrayList1.add(2,"element4");
        
        System.out.println("**Elements of arrayList1 after add**");
        for(String val : arrayList1)
        {
            System.out.println(val);
        }
    }
}

Output

**Elements of arrayList1 before add**
element1
element2
element3
**Elements of arrayList1 after add**
element1
element2
element4
element3

Leave a Reply

Your email address will not be published. Required fields are marked *