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.
1 |
public E set(int index, E element) |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.javacodeexamples.collections.arraylist; import java.util.ArrayList; public class JavaArrayListReplaceExample { public static void main(String[] args) { //create an ArrayList ArrayList<String> aListLaptops = new ArrayList<String>(); aListLaptops.add("Dell"); aListLaptops.add("IBM"); aListLaptops.add("HP"); aListLaptops.add("Apple"); /* * To replace element in ArrayList, use * set(int index, E element) * method. */ //replace IBM with Lenovo using index String strReplacedElement = aListLaptops.set(1, "Lenovo"); System.out.println(strReplacedElement + " replaced with " + "Lenovo"); //print ArrayList elements for(String laptop : aListLaptops) System.out.println(laptop); } } |
Output
1 2 3 4 5 |
IBM replaced with Lenovo Dell Lenovo HP Apple |
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.