1

my classes:

class Game{
     ArrayList<Block> blocks;
public ArrayList<Block> getBlocks(){return blocks;};
}
class Block{
    if(conditon) {
    game.getBlocks().remove(this);
}
}

I have these classes, the ArrayList contains over 10 Block instances, if the condition for remove the current block in the Block class is true, i need remove this block from the ArrayList, but i got the Exception..

4 Answers4

2

While iterating the Arraylist, you are not allowed to remove any item. If you want to remove an item while iteration, you can add removed item into newly created ArrayList say,. willBeRemovedList after iteration completed you can remove all of them at a time.

Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141
2

ConcurrentModificationException is thrown by iterator because you modified a list and he can't get nextElement because he doesn't know what really happened to list he is iterating over.

for (Block block : blocks) {
  blocks.remove(block);
}

This will throw exception when for loop tries to get next element of modified list, since Iterator is instantiated in the beginning of looping through list, iterator will be unable to choose right next element and will throw exception.

You can however remove current element from list you are iterating, but it should be done though Iterator itself. You would do something like this:

for (Iterator<Block> iterator = blocks.iterator(); iterator.hasNext(); iterator.next()){
  iterator.remove();
}
Shamse Alam
  • 1,285
  • 10
  • 21
Dejan Pekter
  • 705
  • 3
  • 18
1

The documentation of ArrayList class cleanly tells us the reason and how to avoid it:

The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Sage
  • 15,290
  • 3
  • 33
  • 38
0

If a fail-fast iterator detects that a modification has been made during iteration, it throws ConcurrentModificationException, which is an unchecked exception. It is highly probable that you are iterating and modifying your collection in the same loop.

Also, the collections classes in the java.util package all return fail-fast iterators, which means that they assume a collection will not change its contents during the time a thread is iterating through its contents.

Nishant
  • 1,142
  • 1
  • 9
  • 27