java.util.ConcurrentModificationException with iterator

user2219247 picture user2219247 · Jun 6, 2013 · Viewed 38.6k times · Source

I know if would be trying to remove from collection looping through it with the simple loop I will be getting this exception: java.util.ConcurrentModificationException. But I am using Iterator and it still generates me this exception. Any idea why and how to solve it?

HashSet<TableRecord> tableRecords = new HashSet<>();

...

    for (Iterator<TableRecord> iterator = tableRecords.iterator(); iterator.hasNext(); ) {
        TableRecord record = iterator.next();
        if (record.getDependency() == null) {
            for (Iterator<TableRecord> dependencyIt = tableRecords.iterator(); dependencyIt.hasNext(); ) {
                TableRecord dependency = dependencyIt.next(); //Here is the line which throws this exception
                if (dependency.getDependency() != null && dependency.getDependency().getId().equals(record.getId())) {
                    tableRecords.remove(record);
                }
            }
        }
    }

Answer

Arnaud Denoyelle picture Arnaud Denoyelle · Jun 6, 2013

You must use iterator.remove() instead of tableRecords.remove()

You can remove items on a list on which you iterate only if you use the remove method from the iterator.

EDIT :

When you create an iterator, it starts to count the modifications that were applied on the collection. If the iterator detects that some modifications were made without using its method (or using another iterator on the same collection), it cannot guarantee anymore that it will not pass twice on the same element or skip one, so it throws this exception

It means that you need to change your code so that you only remove items via iterator.remove (and with only one iterator)

OR

make a list of items to remove then remove them after you finished iterating.