Skip to content

Java ArrayList replace element at specified index example

Java ArrayList replace element at specified index example shows how to replace element at specified index in Java ArrayList using the set method.

How to replace an element at the specified index in Java ArrayList?

ArrayList is an index based collection. That means ArrayList elements can be accessed by specifying the index. To replace an element at the specified index of ArrayList, use the set method.

The set method replaces an element at the specified index with the given new element. This method returns the old element that was replaced by this method.

Java ArrayList replace element example

Output

As you can see from the output, we specified index as 1 in the set method to replace “IBM” with “Lenovo” in the ArrayList. ArrayList index starts from 0 so the first element of ArrayList is located at index 0, not 1.

Please also note that the  set method of ArrayList may throw IndexOutOfBoundsException if the specified index is out of the range of the ArrayList. That is if the index is less than 0 or index is greater than or equal to the size of the ArrayList. Make sure to check the size of the ArrayList, before calling the set method to avoid the exception.

This example is a part of the Java ArrayList tutorial with examples.

Please let me know your views in the comments section below.

About the author

Leave a Reply

Your email address will not be published.