Adding elements in the middle of an ArrayList in Java

Java 8Object Oriented ProgrammingProgramming

Elements can be added in the middle of an ArrayList by using the java.util.ArrayList.add() method. This method has two parameters i.e. the 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, "Apple");
      aList.add(1, "Mango");
      aList.add(2, "Banana");
      aList.add(1, "Melon");
      aList.add(3, "Guava");
      System.out.println("The ArrayList elements are: " + aList);
   }
}

Output

The ArrayList elements are: [Apple, Melon, Mango, Guava, Banana]

Now let us understand the above program.

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

List aList = new ArrayList();
aList.add(0, "Apple");
aList.add(1, "Mango");
aList.add(2, "Banana");
aList.add(1, "Melon");
aList.add(3, "Guava");
System.out.println("The ArrayList elements are: " + aList);
raja
Published on 16-Jan-2019 06:33:06
Advertisements