In this article, we will learn how to add an element to a particular Index of ArrayList in Java programming language.
Java Program to Add Element at Particular Index of ArrayList
This can be done by using a simple built-in method add()
.
It can be used in two variants –
- When we have to simply add an element at the end of ArrayList.
- When we have to add an element at the specified index.
Syntax:
public void add(int index,Object element)
Parameters:
- Particular Index at which element to be added.
- The element that should be added.
Let’s see the program to understand it clearly.
Method: Java Program to Add Element at Particular Index of ArrayList By Using add() Method
Approach –
- Create an ArrayList say
al
and add elements into it usingadd()
method. - Use the
add()
method for both the variants as given below. - Display the updated ArrayList.
Program:
import java.util.ArrayList; public class Main { public static void main(String[] args) { // ArrayList of String type ArrayList<String> al = new ArrayList<String>(); // simply add() methods that adds elements at the end al.add("This"); al.add("is"); al.add("a"); al.add("Sentence"); //printing arraylist before adding any new element at any index System.out.println("Elements before adding at Particular Index:"+ al); //Now, add an element to any position say 1 (position not Index) //So, 1st position = 0 index as indexing starts from 0 al.add(0,"Hello"); System.out.println("Elements after adding at Particular Index:"+ al); //again add an element to any position say 6 = 5th Index al.add(5, "Okay"); //Print System.out.println("Elements after adding Program string :"+ al); } }
Output: Elements before adding at Particular Index:[This, is, a, Sentence] Elements after adding at Particular Index:[Hello, This, is, a, Sentence] Elements after adding Program string :[Hello, This, is, a, Sentence, Okay]
Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.