How to replace element in an ArrayList?

We have seen how to add and remove elements from ArrayList in java. But sometimes, there may be a situation when we want to replace the element in ArrayList. We can use set(int index, E element) to replace the element.

set(int index, E element)

The set(index, E element) method is used to set the specified element at the specified index value. is used to replace the element at the specified position in ArrayList with the specified element. It returns the element after replacement.

E set(int index, E element)

Where, E represents the type of elements in ArrayList .
index, index of the element to return.
throw, IndexOutOfBoundsException if index is invalid.

import java.util.ArrayList;
public class ArraylistExample 
{
	public static void main(String[] args) 
        {
		ArrayList<String> listOfNames = new ArrayList<String>();
		listOfNames.add("JAVA");
		listOfNames.add("GOAL");
		listOfNames.add("RAVI");
				
		listOfNames.set(1, "SITE");
				
		for(String name : listOfNames)
		   System.out.println(name);
	}
}

Output: JAVA
SITE
RAVI

Leave a Comment