In this tutorial, we'll learn how to insert an object in an ArrayList at a specific position.
If we want to add an element to a specific position to an ArrayList we can use the add(int index, E element) method which is provided through the implementation of the interface of List<E>. This method let us add an element at a specific index.
It can also throw an IndexOutOfBoundsException in case the index is out of range (index < 0 or index > size()). This means we can't use it to add an item at position 4 if we've only 4 items in an ArrayList since we start to count with 0. We'd have to use the standard add(E e) method instead here.
First, we'll create a new ArrayList and add four elements to it:
List<Integer> integers = new ArrayList<>(); integers.add(5); integers.add(6); integers.add(7); integers.add(8); System.out.println(integers);
This will result into:
Now, if we add another element at index 1:
The ArrayList internally will first move the objects starting at the given index:
This works cause ArrayList is a growable array that automatically resizes the capacity if needed:
And then add the new item at the given index:
Adding in a specific index will result in an operations performance of O(n/2) on average for an ArrayList. A LinkedList, for example, has a complexity of O(n/4) on average and O(1) if an index is 0. So we need to have a closer look at LinkedList if we heavily rely on adding elements at specific positions.
We can also see that the ordering of the elements isn't correct anymore. When we manually add items at specific positions, this is something we often want to achieve. Otherwise, we could use integers.sort(Integer::compareTo) to sort the ArrayList again or implement our own Comparator.
In this article, we discussed the add(int index, E element) method so we can add a new element at a specific position to an ArrayList<E>. We've to take care to stay inside the index bounds of the ArrayList and make sure that we permit the correct object.
All of the code snippets mentioned in the article can be found over on GitHub.