Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

Through this tutorial, we’ll take a look at how to replace an element at a specific index in a Java ArrayList.

2. Common Practice

To replace an existing element, First, we need to find the exact position of that element in the ArrayList. This position is what we call the index. Then, we can replace the old element with a new one.

The most common way to replace an element in Java ArrayList is to use the set (int index, Object element) method. The set() method takes two parameters: the index of the existing item and the new item.

The index of an ArrayList is zero-based. Thus, to replace the first element, 0 must be the index passed as a parameter.

The IndexOutOfBoundsException will occur if the provided index is out of bounds.

3. Implementation

Let’s see through an example how to replace an element in Java ArrayList at a specific index.

List<Integer> EXPECTED = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

List<Integer> aList = new ArrayList<>(Arrays.asList(1, 2, 7, 4, 5));
aList.set(2, 3);

assertThat(aList).isEqualTo(EXPECTED);

First, we create an ArrayList with five elements. Then, we replace the third element with the value 7, having index 2 with 3. Finally, we can see that index 2 with value 7 is removed from the list and updated with the new value 3. Also, note that the list size is not impacted.

4. Conclusion

In this quick article, we learned how to replace an element at a specific index in Java ArrayList. Furthermore, you can use this method with any other List type like LinkedList. Just make sure that the List you are using is not immutable.

As always, the complete source code for this article can be found over on GitHub.

Course – LS – All

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – REST with Spring (eBook) (everywhere)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.