Search code examples
javaexceptionhashmapconcurrentmodification

How can I iterate over an object while modifying it in Java?


Possible Duplicates:
Java: Efficient Equivalent to Removing while Iterating a Collection
Removing items from a collection in java while iterating over it

I'm trying to loop through HashMap:

Map<String, Integer> group0 = new HashMap<String, Integer>();

... and extract every element in group0. This is my approach:

// iterate through all Members in group 0 that have not been assigned yet
for (Map.Entry<String, Integer> entry : group0.entrySet()) {

    // determine where to assign 'entry'
    iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
    if (iEntryGroup == 1) {
        assign(entry.getKey(), entry.getValue(), 2);
    } else {
        assign(entry.getKey(), entry.getValue(), 1);
    }
}

The problem here is that each call to assign() will remove elements from group0, thus modifying its size, thus causing the following error:

Exception in thread "main" java.util.ConcurrentModificationException
    at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
    at java.util.HashMap$EntryIterator.next(HashMap.java:834)
    at java.util.HashMap$EntryIterator.next(HashMap.java:832)
    at liarliar$Bipartite.bipartition(liarliar.java:463)
    at liarliar$Bipartite.readFile(liarliar.java:216)
    at liarliar.main(liarliar.java:483)

So... how can I loop through the elements in group0 while it's dynamically changing?


Solution

  • Others have mentioned the correct solution without actually spelling it out. So here it is:

    Iterator<Map.Entry<String, Integer>> iterator = 
        group0.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, Integer> entry = iterator.next();
    
        // determine where to assign 'entry'
        iEntryGroup = hasBeenAccusedByGroup(entry.getKey());
    
        if (iEntryGroup == 1) {
            assign(entry.getKey(), entry.getValue(), 2);
        } else {
            assign(entry.getKey(), entry.getValue(), 1);
        }
    
        // I don't know under which conditions you want to remove the entry
        // but here's how you do it
        iterator.remove();
    }
    

    Also, if you want to safely change the map in your assign function, you need to pass in the iterator (of which you can only use the remove function and only once) or the entry to change the value.