Add an element to specified index of ArrayList in Java


An element can be added to the specified index of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the specific index at which to insert the element in the ArrayList and the element itself. If there is an element already present at the index specified by ArrayList.add() then that element and all subsequent elements shift to the right by one.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.ArrayList;
import java.util.List;
public class Demo {
   public static void main(String args[]) throws Exception {
      List aList = new ArrayList();
      aList.add(0, "Dog");
      aList.add(1, "Cat");
      aList.add(2, "Horse");
      aList.add(2, "Pig");
      aList.add(3, "Cow");
      System.out.println("The ArrayList elements are: " + aList);
   }
}

Output

The ArrayList elements are: [Dog, Cat, Pig, Cow, Horse]

Now let us understand the above program.

The ArrayList aList is created. Then ArrayList.add() is used to add the elements at the specified index in the ArrayList. Finally, the ArrayList is displayed. A code snippet which demonstrates this is as follows −

List aList = new ArrayList();
aList.add(0, "Dog");
aList.add(1, "Cat");
aList.add(2, "Horse");
aList.add(2, "Pig");
aList.add(3, "Cow");
System.out.println("The ArrayList elements are: " + aList);

Updated on: 30-Jul-2019

437 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements