循环列表与删除 [英] loop on list with remove

查看:113
本文介绍了循环列表与删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    for (String fruit : list)
    {
        if("banane".equals(fruit))
            list.remove(fruit);
        System.out.println(fruit);
    }

这里是一个带有remove指令的循环。
在执行时,我得到一些ConcurrentModificationException,在控制台输出下面:

Here a loop with remove instruction. At execution time, I get some ConcurrentModificationException, below the console output:

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)
at Boucle.main(Boucle.java:14)
abricot
banane

问题:如何删除一些带有循环的元素?

Question: How to remove some element with a loop?

推荐答案

您需要直接使用迭代器, 。

You need to use the iterator directly, and remove the item via that iterator.

for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
    String fruit = iterator.next();
    if ("banane".equals(fruit)) {
        iterator.remove();
    }
    System.out.println(fruit);
}

这篇关于循环列表与删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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