There is nothing wrong with the idea of modifying an element inside a list while traversing it (don't modify the list itself, that's not recommended), but it can be better expressed like this:

for (int i = 0; i < letters.size(); i++) {
    letters.set(i, "D");
}

At the end the whole list will have the letter "D" as its content. It's not a good idea to use an enhanced for loop in this case, you're not using the iteration variable for anything, and besides you can't modify the list's contents using the iteration variable.

Notice that the above snippet is not modifying the list's structure - meaning: no elements are added or removed and the lists' size remains constant. Simply replacing one element by another doesn't count as a structural modification. Here's the link to the documentation quoted by @ZouZou in the comments, it states that:

A structural modification is any operation that adds or deletes one or more elements, or explicitly resizes the backing array; merely setting the value of an element is not a structural modification

Answer from Óscar López on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-replace-an-element-in-a-list
Java Program to Replace an Element in a List - GeeksforGeeks
January 7, 2026 - Example:This program illustrates how to replace an element in a list while iterating using ListIterator. ... import java.util.ArrayList; import java.util.ListIterator; class GFG { public static void main(String[] args) { ArrayList<String> list1 = new ArrayList<>(); list1.add("Welcome"); list1.add("to"); list1.add("GFG"); list1.add("Learn"); list1.add("here"); System.out.println("Original List : " + list1); ListIterator<String> listIterator = list1.listIterator(); while (listIterator.hasNext()) { int position = listIterator.nextIndex(); if (position == 3) { listIterator.set("Geeks For Geeks"); } listIterator.next(); } System.out.println("Modified List : " + list1); } }
🌐
TutorialsPoint
tutorialspoint.com › replace-an-element-in-an-arraylist-using-the-listiterator-in-java
Replace an element in an ArrayList using the ListIterator in Java
An element in ArrayList can be replaced using the ListIterator method set(). This method has a single parameter i.e. the element that is to be replaced and the set() method replaces it with the last element returned by the next() or previous() methods. A program that demonstrates this is given ...
🌐
Stack Overflow
stackoverflow.com › questions › 64232317 › how-can-i-replace-a-value-in-a-list-using-an-iterator-java
How can I replace a value in a List using an iterator ( Java ) - Stack Overflow
public static void main(String args[]) { Scanner input = new Scanner (System.in); System.out.println("Enter in list"); String s = input.nextLine(); List<String> list = new ArrayList<String>(Arrays.asList(s.split(" "))); String replacewith; String replace; replacewith = list.get(list.size()-1); replace = list.get(list.size()-2); Iterator<String> iterator = list.iterator(); int i = 0; while(iterator.hasNext()) { String value = iterator.next(); if(value.equals(replace)) { iterator.remove(); list.add(i,replacewith); } i++; } System.out.println(list); }
🌐
TutorialsPoint
tutorialspoint.com › article › replace-an-element-from-a-java-list-using-listiterator
Replace an element from a Java List using ListIterator
ListIterator<String>iterator = list.listIterator(); iterator.next(); Replace the element in the List with set() method.
🌐
GeeksforGeeks
geeksforgeeks.org › java › replace-an-element-from-arraylist-using-java-listiterator
Replace an Element From ArrayList using Java ListIterator - GeeksforGeeks
April 3, 2023 - Now, using a ListIterator, we will iterate to the last element of the list and then replace it - ListIterator<String> iterator = name.listIterator(); while(iterator.hasNext()) { iterator.next(); } iterator.set("Mohit"); ... // java program to ...
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java ArrayList Insert/Replace At Index - Java Code Geeks
January 2, 2022 - It is allowed to update the values of the array list based on the condition while iterating it with the help of set() method. Example 5 · In the below example, if the number is divisible by 5 then update the value to -1 otherwise do not replace ...
Find elsewhere
🌐
Java67
java67.com › 2016 › 08 › how-to-replace-element-of-arraylist-in-java.html
How to replace an element of ArrayList in Java? Example | Java67
I think you can use a for-loop to find that certain item that matches certain criteria and then using the index from the for-loop you insert the item to the list at this index.Delete ... Yes, you can iterate through an ArrayList using Iterator, for-each or just for loop but becareful if you are removing elements as it can cause ConcurrentModficiationException.
Top answer
1 of 4
28

The second version would be better. Internally they are the same in the end, but the second actually allows you to modify the list, while the first one will throw a ConcurrentModificationException.

But then you are using the Iterator in a wrong way. Here is how you do it correctly:

for (final ListIterator<String> i = list.listIterator(); i.hasNext();) {
  final String element = i.next();
  i.set(element + "yaddayadda");
}

The iterator is the one that needs to modify the list as it is the only one that knows how to do that properly without getting confused about the list elements and order.

Edit: Because I see this in all comments and the other answers:

Why you should not use list.get, list.set and list.size in a loop

There are many collections in the Java collections framework, each on optimized for specific needs. Many people use the ArrayList, which internally uses an array. This is fine as long as the amount of elements does not change much over time and has the special benefit that get, set and size are constant time operations on this specific type of list.

There are however other list types, where this is not true. For example if you have a list that constantly grows and/or shrinks, it is much better to use a LinkedList, because in contrast to the ArrayList add(element) is a constant time operation, but add(index, element), get(index) and remove(index) are not!

To get the position of the specific index, the list needs to be traversed from the first/last till the specific element is found. So if you do that in a loop, this is equal to the following pseudo-code:

for (int index = 0; index < list.size(); ++index) {
  Element e = get( (for(int i = 0; i < size; ++i) { if (i == index) return element; else element = nextElement(); }) );
}

The Iterator is an abstract way to traverse a list and therefore it can ensure that the traversal is done in an optimal way for each list. Test show that there is little time difference between using an iterator and get(i) for an ArrayList, but a huge time difference (in favor for the iterator) on a LinkedList.

2 of 4
12

EDIT: If you know that size(), get(index) and set(index, value) are all constant time operations for the operations you're using (e.g. for ArrayList), I would personally just skip the iterators in this case:

for (int i = 0; i < list.size(); i++) {
    list.set(i, list.get(i) + " blah");
}

Your first approach is inefficient and potentially incorrect (as indexOf may return the wrong value - it will return the first match). Your second approach is very confusing - the fact that you call next() twice and previous once makes it hard to understand in my view.

Any approach using List.set(index, value) will be inefficient for a list which doesn't have constant time indexed write access, of course. As TwoThe noted, using ListIterator.set(value) is much better. TwoThe's approach of using a ListIterator is a better general purpose approach.

That said, another alternative in many cases would be to change your design to project one list to another instead - either as a view or materially. When you're not changing the list, you don't need to worry about it.

🌐
Benchresources
benchresources.net › home › java › java – how to add/remove/modify an element in list while iterating ?
Java - How to add/remove/modify an element in List while iterating ? - BenchResources.Net
July 20, 2022 - Original Fruit List :- [Melons, Mango, Apple, Cherry, Grapes] Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1013) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:967) at in.bench.resources.listiterator.AddRemoveWhileIteratingUsingForEachLoop .main(AddRemoveWhileIteratingUsingForEachLoop.java:23) Here, we are trying to remove an element while iterating List using Iterator interface which also throws ConcurrentModificationException
Top answer
1 of 7
91

The list is maintaining an object reference to the original value stored in the list. So when you execute this line:

Integer x = i.next();

Both x and the list are storing a reference to the same object. However, when you execute:

x = Integer.valueOf(9);

nothing has changed in the list, but x is now storing a reference to a different object. The list has not changed. You need to use some of the list manipulation methods, such as

list.set(index, Integer.valueof(9))

Note: this has nothing to do with the immutability of Integer, as others are suggesting. This is just basic Java object reference behaviour.


Here's a complete example, to help explain the point. Note that this makes use of the ListIterator class, which supports removing/setting items mid-iteration:

import java.util.*;

public class ListExample {

  public static void main(String[] args) {

    List<Foo> fooList = new ArrayList<Foo>();
    for (int i = 0; i < 9; i++)
      fooList.add(new Foo(i, i));

    // Standard iterator sufficient for altering elements
    Iterator<Foo> iterator = fooList.iterator();

    if (iterator.hasNext()) {
      Foo foo = iterator.next();
      foo.x = 99;
      foo.y = 42;
    }

    printList(fooList);    

    // List iterator needed for replacing elements
    ListIterator<Foo> listIterator = fooList.listIterator();

    if (listIterator.hasNext()) {
      // Need to call next, before set.
      listIterator.next();
      // Replace item returned from next()
      listIterator.set(new Foo(99,99));
    }

    printList(fooList);
  }

  private static void printList(List<?> list) {
    Iterator<?> iterator = list.iterator();
    while (iterator.hasNext()) {
      System.out.print(iterator.next());
    }
    System.out.println();
  }

  private static class Foo {
    int x;
    int y;

    Foo(int x, int y) {
      this.x = x;
      this.y = y;
    }

    @Override
    public String toString() {
      return String.format("[%d, %d]", x, y);
    }
  }
}

This will print:

[99, 42][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
[99, 99][1, 1][2, 2][3, 3][4, 4][5, 5][6, 6][7, 7][8, 8]
2 of 7
16

Use the set method to replace the old value with a new one.

list.set( 2, "New" );
🌐
How to do in Java
howtodoinjava.com › home › collections framework › java arraylist › replace an existing item in arraylist
Replace an Existing Item in ArrayList
January 12, 2023 - 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.
🌐
Stack Overflow
stackoverflow.com › questions › 23282073 › change-a-list-while-iterating-or-using-a-for-each-loop
java - change a list while iterating or using a for each loop - Stack Overflow
April 25, 2014 - You can call iterator.remove() to savely remove the current item from list. ... Sign up to request clarification or add additional context in comments. ... won't this throw an exception? or does the iterator die and the loop terminate? 2014-04-25T00:32:35.323Z+00:00 ... There won't die anything and it works perfectly fine ;) - This will replace "an" for "a" 2014-04-25T00:34:10.58Z+00:00 ... There is no guarantee that you'll get ConcurrentModificationException. From its JavaDocs "Note that fail-fast behavior cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification.
🌐
Quora
quora.com › While-iterating-the-list-in-Java-can-I-add-an-element-to-the-same-list
While iterating the list in Java, can I add an element to the same list? - Quora
Answer (1 of 2): You can't modify a Collection while iterating over it using an [code ]Iterator[/code], except for [code ]Iterator.remove()[/code]. However, if you use the listIterator() method, which returns a [code ]ListIterator[/code], and iterate over that you have more options to modify. Fr...