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.
Submitted by IncludeHelp, on October 19, 2017

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

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

Java ArrayList Programs »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.