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

后端 未结 5 1231
执笔经年
执笔经年 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 07:40
    List<Apple> apples = appleCart.getApples();
    for (Iterator<Apple> appleIterator = apples.iterator(); appleIterator.hasNext();)
    {
       Apple apple = appleIterator.next();
       if ( apple.isYucky() ) {
         appleIterator.remove();
       }
    }
    
    0 讨论(0)
  • 2021-01-21 07:43

    You could keep a list of items to remove and then remove them after the loop:

    List<Apple> apples = appleCart.getApples();
    List<Apple> badApples = new ArrayList<Apple>();
    for (Apple apple : apples) {
        if (apple.isBad()) {
            badApples.add(apple);
        } else {
    
        eat(apple);
    }
    
    apples.removeAll(badApples);
    
    0 讨论(0)
  • 2021-01-21 07:46

    If you're getting a ConcurrentModificationException, you likely have multiple threads.

    So the full answer includes both using Iterator.remove() and synchronizing access to the collection.

    For example (where lock is synchronized on by all threads that may modify the list):

    synchronized ( lock ) {
       List<Apple> apples = appleCart.getApples();
       for ( Iterator<Apple> it = apples.iterator(); it.hasNext(); )
       {
          Apple a = it.next(); 
          if ( a.hasWorm() ) {
             it.remove();
          }
       }
    }
    
    0 讨论(0)
  • 2021-01-21 08:01

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

      for (Iterator<Apple> appleIterator = Apples.iterator(); appleIterator.hasNext();) {
         Apple apple = appleIterator.next();
         if (apple.isTart()) {
            appleIterator.remove();
         }
      }
    }
    
    0 讨论(0)
  • 2021-01-21 08:02

    Since Java 8 you can now do this: apples.removeIf(apple -> apple.equals(this))

    0 讨论(0)
提交回复
热议问题