我收到以下异常:“java.util.ConcurrentModificationException”

发布于 2024-10-18 08:44:06 字数 298 浏览 7 评论 0原文

当我运行这段代码时,出现“发生异常:java.util.ConcurrentModificationException”。这里有人看到问题是什么吗?

public void mudaDeEstado() {
    Luz luz = new Luz();
    while(this.iterador.hasNext()) {
        luz = (this.iterador.next());
        luz.defineEstado(!luz.acesa());
    }

}

多谢!!

I'm getting a "An exception occurred: java.util.ConcurrentModificationException" when I run this piece of code. Does anyone here see what the problem is?

public void mudaDeEstado() {
    Luz luz = new Luz();
    while(this.iterador.hasNext()) {
        luz = (this.iterador.next());
        luz.defineEstado(!luz.acesa());
    }

}

Thanks a lot!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

歌入人心 2024-10-25 08:44:06

您试图修改迭代器在循环元素时保存的引用。您可以在此处阅读有关他的异常的更多信息

例如,一般情况下不
允许一个线程修改一个
当另一个线程正在收集时
迭代它。一般来说,
迭代的结果未定义
在这种情况下。一些
迭代器实现(包括
所有通用目的的
提供的集合实现
JRE)可能会选择抛出这个
如果此行为是例外
检测到。执行此操作的迭代器是
称为快速失败迭代器,因为它们
快速而干净地失败,而不是
冒任意性、不确定性的风险
在不确定的时间的行为
未来。

最有可能的罪魁祸首是这样的:

luz.defineEstado(!luz.acesa());

You are trying to modify the reference that the iterator holds while looping through the elements. You can read more about his exception here.

For example, it is not generally
permissible for one thread to modify a
Collection while another thread is
iterating over it. In general, the
results of the iteration are undefined
under these circumstances. Some
Iterator implementations (including
those of all the general purpose
collection implementations provided by
the JRE) may choose to throw this
exception if this behavior is
detected. Iterators that do this are
known as fail-fast iterators, as they
fail quickly and cleanly, rather that
risking arbitrary, non-deterministic
behavior at an undetermined time in
the future.

Most probably the culprit here is this:

luz.defineEstado(!luz.acesa());
糖果控 2024-10-25 08:44:06

当您在迭代数据结构时修改数据结构时,会引发此异常。更改数据结构中的元素可以改变迭代元素的方式,因此许多数据结构不允许并发修改。

尝试保留需要更新的元素列表,然后在迭代整个数据结构后返回并更新这些元素。

抱歉,我的措辞有点笼统且含糊不清,但很难用所提供的代码给出具体细节。

This exception is thrown when you modify a data structure while you are iterating through it. Changing the elements in the data structure can change the way one iterates through the elements, so many data structures do not allow concurrent modification.

Try keeping a list of elements that need to be updated and then go back through and update those elements once you have iterated through the entire data structure.

Sorry my wording is kind of general and ambiguous, but it's hard to give specifics with the provided code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文