Q:

Java program to add element at specific index in ArrayList

belongs to collection: Java ArrayList Programs

0

In this program, we are adding 5 elements (100, 200, 300, 400 and 500) to the ArrayList using "add()" method of ArrayList class.

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.

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
  •  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Consider the program

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java program to add elements in ArrayList and prin... >>
<< Java program to create an ArrayList, add elements ...