I want to avoid getting ConcurrentModificationException
. How would I do it?
You can use ListLterator for modifying list during iterating,it provides more functionality than iterator.
The add() method of ListIterator interface is used to insert the given element into the specified list. The element is inserted automatically before the next element may return by next() method.
The size of the List is not being changed, but the object at the index is changing, so technically the List is being modified.
You may use a ListIterator
which has support for a remove/add method during the iteration itself.
ListIterator<Book> iter = books.listIterator(); while(iter.hasNext()){ if(iter.next().getIsbn().equals(isbn)){ iter.add(new Book(...)); } }
Instead of using an iterator, you can use a for loop with an index. For example:
int originalLength = list.length(); for (int i = 0; i < originalLength; i++) { MyType mt = list.get(i); //... processing //... insertions }
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<Integer> L = new LinkedList<Integer>();
L.add(0);
L.add(1);
L.add(2);
for (ListIterator<Integer> i = L.listIterator(); i.hasNext(); ) {
int x = i.next();
i.add(x + 10);
}
System.out.println(L);
}
}
Prints [0, 10, 1, 11, 2, 12]
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With