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.set(1, "SITE");
		for(String name : listOfNames)

Output: JAVA

Leave a Comment

Follow us on Instagram & watch the latest videos on YouTube. Click below social icons to visit our Instagram & YouTube profiles.