Java Program to Add Element at Specific Index in ArrayList

You are currently viewing Java Program to Add Element at Specific Index in ArrayList

Java program to add element at specific index in ArrayList

import java.util.ArrayList;
 
public class ExArrayList {
 
  public static void main(String[] args) {
    ////Creating object of ArrayList
    ArrayList arrList = new ArrayList();
   
    //adding data to the list
    arrList.add("100");
    arrList.add("200");
    arrList.add("300");
    arrList.add("400");
    arrList.add("500");
   
    //ading data to specified index in array list
    //we are adding "Hello" at index 1, "World" at index 2 and "Hi there" at index 4
    arrList.add(1,"Hello");
    arrList.add(2,"World");
    arrList.add(4,"Hi there");
    
    System.out.println("Array List elements: ");
    //display elements of ArrayList
    for(int iLoop=0; iLoop < arrList.size(); iLoop++)
      System.out.println(arrList.get(iLoop));
   
  }
}

Output

Array List elements: 
100
Hello
World
200
Hi there
300
400
500

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply