Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to Add an Element at Particular Index in Java ArrayList?

  • Last Updated : 12 Jul, 2021

ArrayList.add() method is used to add an element at particular index in Java ArrayList.

Syntax:

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

public void add(int index, Object element) ;

Parameters: 

  • index  -position at which the element has to be inserted. The index is zero-based.
  • element – the element to be inserted at the specified position.

Exception: throws IndexOutOfBoundsException which occurs when the index is trying to be accessed which isn’t there in the allocated memory block. In java, this exception is thrown when a negative index is accessed or an index of memory space. Here particularly when an index greater than the size of ArrayList is trying to be fetched or the insertion of an element at an index greater than size() of ArrayList is fetched.
 



Example:

For a list of string

list=[A,B,C]

list.add(1,”D”);

list.add(2,”E”);

list=[A,D,E,B,C]

For a list of integers

LIST=[1,2,3]

list.add(2,4);

list=[1,2,4,3]

Implementation:

Java




// Adding an Element at Particular
// Index in Java ArrayList
import java.io.*;
import java.util.ArrayList;
 
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating an ArrayList
        ArrayList<String> list = new ArrayList<>();
 
        // Adding elements to ArrayList
        // using add method for String ArrayList
        list.add("A");
        list.add("B");
        list.add("C");
 
        /* Index is zero based */
 
        // 3 gets added to the 1st position
        list.add(1, "D");
 
        // 4 gets added to the 2nd(position)
        list.add(2, "E");
 
        // Displaying elements in ArrayList
        System.out.println(list);
    }
}

 
 

Output
[A, D, E, B, C]

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!