相关疑难解决方法(0)

带迭代器的java.util.ConcurrentModificationException

我知道如果试图通过简单的循环从集合中删除循环,我会得到这个异常: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)

java iterator removechild concurrentmodification

24
推荐指数
1
解决办法
3万
查看次数