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

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

1 thought on “How to replace existing element in ArrayList”

  1. Hi Team,
    Thanks for your Tutorial.

    One request to add set(index, object) in the ArrayList Methods which is now available currently. Please include and help us.

    Thanks.
    Gnanavelu.

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and related technologies, the best practices, algorithms, and interview questions.