java - 迭代列表时删除元素

标签 java collections foreach iterator

我尝试使用 Iterator 从列表中删除元素,但出现以下异常:

java.util.NoSuchElementException

代码:

for (Iterator<Punk> iter = list.listIterator(); iter.hasNext(); ) {
    Punk p = iterator.next();

    if (some condition ) {
        iterator.remove();
    }

    index += 1;
}

我只是每次在循环中使用一次iterator.next(),以便它移动到下一个元素。有人可以帮忙吗?提前致谢!如有任何帮助,我们将不胜感激。

最佳答案

您正在使用iterator,但您使用iter迭代此列表。确保您的变量名称正确。

for (Iterator<Punk> iter = list.listIterator(); iter.hasNext(); ) {
    Punk p = iter.next();

    if (some condition ) {
        iter.remove();
    }
}

关于java - 迭代列表时删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673751/

相关文章:

java - Craftbukkit 玩家计数消息插件编码错误

java - 从 apigee api 代理 : Class is not a function, 中的 javascript 创建 java 对象它是对象

java - 将 char 集合转换为不带逗号和方括号的字符串

c# - LINQ - 查找给定列表中的所有项目都包含在 icollection 中的所有记录

C# - foreach 循环 - 良好实践

javascript - Angular4/Typescript 中的 Angular ForEach?

java - 为什么可以轻松地重建Java类文件

java - 为什么 JPA 更新 OrderColumn 而不是在创建时设置它?

java - Collections.max() 不正确的参数

php - 只为 foreach 循环显示一条消息