Search code examples
javaconcurrentmodification

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());
        luz.defineEstado(!luz.acesa());
    }

}

Thanks a lot!!


Solution

  • 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.