I want to avoid getting ConcurrentModificationException
. How would I do it?
You want to use a ListIterator
. You can get one of these from any kind of list, though for efficiency you probably want to get one from a LinkedList
.
import java.util.*;
class TestListIterator {
public static void main(String[]args) {
List L = new LinkedList();
L.add(0);
L.add(1);
L.add(2);
for (ListIterator i = L.listIterator(); i.hasNext(); ) {
int x = i.next();
i.add(x + 10);
}
System.out.println(L);
}
}
Prints [0, 10, 1, 11, 2, 12]
.