Is there an accepted best practice in Java for deleting a list element while iterating over the list?

后端 未结 5 1230
执笔经年
执笔经年 2021-01-21 07:15

I\'m finding conflicting advice over the best way to avoid a ConcurrentModificationException while doing this:

    List Apples = appleC         


        
5条回答
  •  北海茫月
    2021-01-21 08:01

    Yes, use an Iterator. Then you could use its remove method.

      for (Iterator appleIterator = Apples.iterator(); appleIterator.hasNext();) {
         Apple apple = appleIterator.next();
         if (apple.isTart()) {
            appleIterator.remove();
         }
      }
    }
    

提交回复
热议问题