开发者

I get the following exception: "java.util.ConcurrentModificationException"

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());
        lu开发者_JS百科z.defineEstado(!luz.acesa());
    }

}

Thanks a lot!!


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜