sneppets-java8

Java – Replace element in ArrayList at specific index

This tutorial shows you how to replace element in ArrayList at specific index using set(int index, E element) method of List interface Java.

Replace element in ArrayList at specific index

The below example shows you how to replace an existing element in the array list. The following is the approach that we need to follow in order to replace an element in ArrayList.

  • First get the index value of the existing element which needs to be replaced with new element using indexOf() method.
  • Next, you need to use set(int index, E element) method to replace the element.
package com.sneppets.example;

import java.util.ArrayList;

public class ArrayListReplaceElementExample {
	
	public static void main (String[] args) {
		
		ArrayList<String> arrList = new ArrayList<>();
		arrList.add("a");
		arrList.add("b");
		arrList.add("c");
		arrList.add("d");
		arrList.add("e");
		
		System.out.println("Array List Before : " + arrList);
		
		System.out.println("Replace d with x...");
                //step 1
		int index = arrList.indexOf("d");
                //step 2
		arrList.set(index, "x");
		System.out.println("Array List After : " + arrList);		
		
	}

}

Let’s say in the above example you wanted to replace element “d” with “x“, then first find the index value of element “d” and use the index value and the new element “x” in set() method to replace.

Note, set(index, element) method replaces the element at the specified position (index) in that list with the specified element (element).

Output

Array List Before : [a, b, c, d, e]
Replace d with x...
Array List After : [a, b, c, x, e]

Also See

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments