带有迭代器的 java.util.ConcurrentModificationException

标签 java iterator removechild concurrentmodification

我知道是否会尝试通过简单的循环从集合中删除,我会得到这个异常:java.util.ConcurrentModificationException。但我正在使用迭代器,它仍然会产生这个异常。知道为什么以及如何解决它吗?

HashSet<TableRecord> tableRecords = new HashSet<>();

...

    for (Iterator<TableRecord> iterator = tableRecords.iterator(); iterator.hasNext(); ) {
        TableRecord record = iterator.next();
        if (record.getDependency() == null) {
            for (Iterator<TableRecord> dependencyIt = tableRecords.iterator(); dependencyIt.hasNext(); ) {
                TableRecord dependency = dependencyIt.next(); //Here is the line which throws this exception
                if (dependency.getDependency() != null && dependency.getDependency().getId().equals(record.getId())) {
                    tableRecords.remove(record);
                }
            }
        }
    }

最佳答案

您必须使用 iterator.remove() 而不是 tableRecords.remove()

只有在迭代器中使用 remove 方法时,才能删除要迭代的列表中的项目。

编辑:

当您创建迭代器时,它会开始计算应用于集合的修改。如果迭代器检测到一些修改没有使用它的方法(或者在同一个集合上使用另一个迭代器),它不能再保证它不会在同一个元素上传递两次或跳过一个,所以它抛出这个异常

这意味着您需要更改代码,以便仅通过 iterator.remove 删除项目(并且只有一个迭代器)

列出要删除的项目,然后在完成迭代后将其删除。

关于带有迭代器的 java.util.ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16965484/

相关文章:

java - 无法在 android 上运行 runtime.exec

javascript - 使用 jquery 删除 div

c# - 从一组相似节点中删除一个节点/元素

scala - 在 Scala 中继续阅读 stdin 直到 "END"?

c++ - 为基类设计一个基迭代器

javascript - 如何使用 JavaScript(js) 克隆和删除 html 表单?

java - 在Android中,我如何按日期对数组项进行分组?

java - 将操作事件处理程序添加到文本字段 java fx

java - 在卡片布局中定位组件

c++ - 为什么 range::sort 返回迭代器?