Java - 在迭代时将元素添加到列表中

2022-01-10 00:00:00 arraylist iterator java

我想避免得到 ConcurrentModificationException.我该怎么做?

I want to avoid getting ConcurrentModificationException. How would I do it?

推荐答案

您可以使用 ListIterator,它在迭代过程中支持删除/添加方法.

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

相关文章