Collections

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 set method.

How to replace element at specified index in Java ArrayList?

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

set method replaces an element at the specified index with the given element. This method returns the element which 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, set method of ArrayList may throw IndexOutOfBoundsException if the specified index is out of the range of the ArrayList. That is if 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 invoking the set method to avoid the exception.

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

Join 1000+ fellow learners! Enter your email address below: