Trup Trup - 1 month ago 11
Java Question

Java - adding elements to list while iterating over it

I want to avoid getting

ConcurrentModificationException
. How would I do it?

Answer

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(...));
    }
}
Comments