Java - adding elements to list while iterating over it

前端 未结 5 1780
花落未央
花落未央 2020-12-10 00:53

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

5条回答
  •  孤城傲影
    2020-12-10 01:52

    You may use a ListIterator which has support for a remove/add method during the iteration itself.

    ListIterator iter = books.listIterator();
    while(iter.hasNext()){
        if(iter.next().getIsbn().equals(isbn)){
            iter.add(new Book(...));
        }
    }
    

提交回复
热议问题