Java program to add element at specific index in ArrayList

In this program, we are going to learn create an ArrayList, adding elements at specific index and print them on output screen. By IncludeHelp Last updated : December 31, 2023

Problem statement

Given an ArrayList, write a Java program to add element at specific index in it.

Adding element at specific index in ArrayList

To add elements at the specific index, use the add() method of the ArrayList class by passing the index and the element.

Syntax of ArrayList.add() method

ArrayList.add(index, element);

Here,

  • index - is the index of the element, where we have to add an element
  • element - is the element (item), which has to be added

Java program to add element at specific index in ArrayList

In this program, we are adding 5 elements (100, 200, 300, 400 and 500) to the ArrayList.

Further, we are adding two more elements which are string type; here we will add "Hello" at index 1, "World" at index 2 and "Hi there" at index 4.

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

The output of the above example is:

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

Java ArrayList Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.