Add Element(s) at Specified Index in ArrayList

Use ArrayList.add(int index, E element) method to add an element to a specific index of ArrayList. The other elements in the list move to their next index location, and the list size increases by 1.

1. ArrayList.add() and addAll() APIs

The ArrayList.add() method inserts the specified element at the specified position in this list. It shifts the element currently at that position (if any) and any subsequent elements to the right (will add one to their indices). Note that indices start from 0.

The add() does not return any value.

void ArrayList.add(index, itemToAdd);

If we have to add multiple items to the list, we can use the method addAll(), which takes another collection and the index location. It returns true if the items have been successfully, else returns false.

boolean ArrayList.addAll(index, collectionOfItems);

2. Examples

Let us take an example of adding an item at the index position1.

ArrayList<String> namesList = new ArrayList<>(Arrays.asList("alex", "brian", "charles"));

namesList.add(1, "Lokesh");

System.out.println(namesList);  //[alex, Lokesh, brian, charles]

Similarly, we can add multiple items to the list by passing another List to the addAll() method.

In the following example, we add the new items at the start of the list. It moves all the existing items to their right.

ArrayList<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));

list.addAll(0, List.of("1", "2", "3"));

System.out.println(list);  //[1, 2, 3, a, b, c]

3. Throws IndexOutOfBoundsException

If the argument index is out of bounds, the add() method throws IndexOutOfBoundsException.

Assertions.assertThrows(IndexOutOfBoundsException.class, () -> {

  namesList.add(10, "Lokesh");

Happy Learning !!

Read More: ArrayList Java Docs

Sourcecode on Github

Leave a Reply

Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial