在迭代列表时删除列表元素是否存在Java中公认的最佳实践? [英] Is there an accepted best practice in Java for deleting a list element while iterating over the list?

查看:113
本文介绍了在迭代列表时删除列表元素是否存在Java中公认的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现在执行此操作时避免 ConcurrentModificationException 的最佳方法存在冲突的建议:

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

    List<Apple> Apples = appleCart.getApples();
    for (Apple apple : Apples)
    {
        delete(apple);
    }

我倾向于使用 Iterator 代替 List 并调用其 remove 方法。

I'm leaning towards using an Iterator in place of a List and calling its remove method.

这在这里最有意义吗?

推荐答案

是的,使用迭代器。然后你可以使用它的删除方法。

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

这篇关于在迭代列表时删除列表元素是否存在Java中公认的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆