How to replace existing element in ArrayList

Learn to update or replace existing element in ArrayList with a given new element or value, using set (int index, Object element) method.

Replace existing element in ArrayList

To replace an existing element, we must find the exact position (index) of the element in arraylist. Once we have the index, we can use set() method to update the replace the old element with new element.

  1. Find index of existing element using indexOf() method.
  2. Use set(index, object) to update new element.

ArrayList set() method example

Java program to update arraylist object and set value at index.

public class ArrayListExample 
{
    public static void main(String[] args) 
    {
        ArrayList<String> list = new ArrayList<>();
        
        list.add("A");
        list.add("B");
        list.add("C");
        list.add("D");
        
        System.out.println(list);

        
        //Replace C with C_NEW


        //1 - In multiple steps
        
        int index = list.indexOf("C");
        
        list.set(index, "C_NEW");
        
        System.out.println(list);


        //2 - In single step replace D with D_NEW

        list.set( list.indexOf("D") , "D_NEW");

        System.out.println(list);
    }
}

Program output.

[A, B, C, D]
[A, B, C_NEW, D]
[A, B, C_NEW, D_NEW]

Happy Learning !!

Read More:

A Guide to Java ArrayList
ArrayList Java Docs

Leave a Reply

1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.