Replace an Existing Item in ArrayList

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

1. Replacing an Existing Item

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

  • Find the index of an existing item using indexOf() method.
  • Use set(index, object) to update with the new item.

Note that the IndexOutOfBoundsException will occur if the provided index is out of bounds.

2. Example

The following Java program contains four strings. We are updating the value of “C” with “C_NEW”.

    ArrayList<String> list = new ArrayList<>(List.of("A", "B", "C", "D"));
    
    int index = list.indexOf("C");
    list.set(index, "C_NEW");
    
    Assertions.assertEquals("C_NEW", list.get(index));

    We can make the whole replacing process in a single statement as follows:

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

    Happy Learning !!

    Read More:

    A Guide to Java ArrayList
    ArrayList Java Docs

    Leave a Reply

    0 Comments
    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.

    Our Blogs

    REST API Tutorial