0

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?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
cr0078
  • 23
  • 1
  • 8
  • 2
    Possible duplicate of [Iterating through a list, avoiding ConcurrentModificationException when removing in loop](http://stackoverflow.com/questions/223918/iterating-through-a-list-avoiding-concurrentmodificationexception-when-removing) – Turing85 Jan 16 '16 at 13:12
  • @Turing85 This is not a good duplicate, because OP can avoid modifications altogether, instead of making modifications work. – Sergey Kalinichenko Jan 16 '16 at 13:14
  • 1
    It is not a duplication. It adds also elements to the list. Not only remove them. – Davide Lorenzo MARINO Jan 16 '16 at 13:16

3 Answers3

3

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);
    }
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
0

A ConcurrentModificationException is thrown when you try to modify a Collection while iterating over it and without using the method remove of the iterator.

When you use the syntax

for (Team team : mTeams) {

an iterator is created for you.

If you like to delete items from your code you explicitly needs to iterate over an iterator or you need to loop using the old style for loop. For example

for (int i = 0; i < mTeams.size(); i++) {

    // Here you can use add and remove on the list without problems
}

or (but not useful here because you need also to add elements, not only remove them)

Iterator<Team> iterator = mTeams.iterator();
while (iterator.hasNext()) {
    Team team = iterator.next());
    // Here you can use iterator.remove but you can't add
}
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

you can't do structural(add/remove) changes in list while iterating. it will throw ConcurrentModificationException. Use iterator to remove or add

M Sach
  • 33,416
  • 76
  • 221
  • 314