Open In App

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

Last Updated : 31 Mar, 2023
Comments
Improve
Suggest changes
3 Likes
Like
Report

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

Syntax:

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:


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

Time Complexity: O(n)
Auxiliary Space: O(1)

As constant extra space is used.
 


Next Article
Practice Tags :

Similar Reads