In this example we will learn how to replace an element which is present in the ArrayList. We will use set(int index, Object obj) method to perform a replace operation. Now lets see how to replace an element in the ArrayList.
- Create a new empty ArrayList.
- Add elements to the ArrayList, using the add() method.
- Use set(index, element), this method will replace an element at the specified index of the arrayList with the given element
import java.util.ArrayList; public class ArrayListReplaceExample { public static void main(String args[]) { // Creating an empty array list ArrayList al = new ArrayList(); //Adding elements to the arraylist al.add("Element1"); al.add("Element2"); al.add("Element3"); System.out.println("List before Replacing element"+al); //Set method will replace the element which is present at the particular index al.set(1,"Java Interview Point"); //List after setting a new element System.out.println("List After Replacing element"+al); } }
Output
List before Replacing element[Element1, Element2, Element3] List After Replacing element[Element1, Java Interview Point, Element3]
Leave a Reply