带迭代器的java.util.ConcurrentModificationException

use*_*247 24 java iterator removechild concurrentmodification

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

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);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Arn*_*lle 38

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

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

编辑:

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

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

要么

制作要删除的项目列表,然后在完成迭代后删除它们.

  • 还是一样. (3认同)