04/07/2012

[Java] ConcurrentModificationException

While iterating over any Collection such as Lists, HashSets, etc.. in Java, you may find the need to add or remove items and in doing so you may encounter the ConcurrentModificationException.

You can solve this by cycling over the collection using an Iterator:

Iterator iterator = [collection].iterator();
while (iterator.hasNext()) {
    [type] element = iterator.next();
    if([conditions]){
       iterator.[method];
    }
}

and then calling the iterator.add() or iterator.remove() method.

Note that in later Java versions you may need to type the Iterator as:

Iterator<[type]> iterator = [collection].iterator();

No comments:

Post a Comment

With great power comes great responsibility