I have a map that maps bytes to sets of bytes. I want to walk through the map and make changes to the set.
private HashMap<Byte, HashSet<Byte>> table;
...
Iterator<Entry<Byte, HashSet<Byte>>> it = table.entrySet().iterator();
while( it.hasNext() ) {
Map.Entry<Byte, HashSet<Byte>> pairs = it.next();
byte node = pairs.getKey();
HashSet<Byte> hSet = pairs.getValue();
Iterator<Byte> setIter = hSet.iterator();
while( setIter.hasNext() ) {
byte sNode = setIter.next(); // Throws a ConcurrentModificationException
...
}
}
This code throws a ConcurrentModificationException when I try to iterate through the sub iterator. What should I do to iterate through, and make changes to, this collection within my map?
I think you get the exception because you modify the set during the iteration (in the lines that were not included into the question). The “fail-fast” iterators are throwing it, if they detect that the structure of the collection has been changed.
http://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html
If you are only deleting from the set while you iterate it, you can use the remove method of the iterator instead of the Set methods. If you also want to add to the set while iterating, you need to create a copy of the Set, and iterate that (but this case is unlikely, you can add to a set without iterating it…)