带有迭代器的 java.util.ConcurrentModificationException

java.util.ConcurrentModificationException with iterator(带有迭代器的 java.util.ConcurrentModificationException)
本文介绍了带有迭代器的 java.util.ConcurrentModificationException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

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

I know if would be trying to remove from collection looping through it with the simple loop I will be getting this exception: java.util.ConcurrentModificationException. But I am using Iterator and it still generates me this exception. Any idea why and how to solve it?

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()

You must use iterator.remove() instead of tableRecords.remove()

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

You can remove items on a list on which you iterate only if you use the remove method from the iterator.

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

When you create an iterator, it starts to count the modifications that were applied on the collection. If the iterator detects that some modifications were made without using its method (or using another iterator on the same collection), it cannot guarantee anymore that it will not pass twice on the same element or skip one, so it throws this exception

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

It means that you need to change your code so that you only remove items via iterator.remove (and with only one iterator)

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

make a list of items to remove then remove them after you finished iterating.

这篇关于带有迭代器的 java.util.ConcurrentModificationException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Reliable implementation of PBKDF2-HMAC-SHA256 for JAVA(PBKDF2-HMAC-SHA256 for JAVA 的可靠实现)
Correct way to sign and verify signature using bouncycastle(使用 bouncycastle 签名和验证签名的正确方法)
Creating RSA Public Key From String(从字符串创建 RSA 公钥)
Why java.security.NoSuchProviderException No such provider: BC?(为什么 java.security.NoSuchProviderException 没有这样的提供者:BC?)
Generating X509 Certificate using Bouncy Castle Java(使用 Bouncy Castle Java 生成 X509 证书)
How can I get a PublicKey object from EC public key bytes?(如何从 EC 公钥字节中获取 PublicKey 对象?)