Search code examples
javaconcurrentmodification

Avoiding ConcurrentModificationException when using nested for-loops in Java


in my program I've created teams(football for example) and now I want to create a method where every team plays a match against all the other teams. My method throws a ConcurrentModificationException. Here it is:

public void playMatches(){
    for (Team team : mTeams) {
        mTeams.remove(team);
        for (Team team1 : mTeams) {
            match(team, team1);
        }
        mTeams.add(team);
    }
}

I'm removing the team itself from mTeams, so that it doesn't play against itself, but this throws the Exception. How can I handle that?


Solution

  • Since you seem to understand what's breaking, let's consider the "how to handle" part of your question. Good news is that you do not need to modify your collection at all.

    Rather than modifying the collection by removing and then adding an item, skip the team from the outer loop when you call match in the inner loop, like this:

    for (Team team : mTeams) {
        for (Team team1 : mTeams) {
            if (team.equals(team1)) continue;
            match(team, team1);
        }
    }