Add element at specific index in ArrayList in Java

In this tutorial, we will learn how to add element at specific index in ArrayList with in example.

ArrayList in Java is a resizable-array implementation of the List interface. ArrayList in Java implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

ArrayList class in Java provides a method add(int index, E element) to add element at specific index in ArrayList. This method inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right (adds one to their indices).

The syntax of add(int index, E element) method is:

index – index at which the specified element is to be inserted.
element – element to be inserted.

IndexOutOfBoundsException – if the index is out of range (index < 0 or index > size())




Related posts

Leave a Comment