Lobot
February 13, 2010, 8:08am
1
OK, I’m not a Java guru, but I have no idea as to what’s going wrong here. Whatever it is, it looks like I’m just misunderstanding something.
Iterator itr = lhm.keySet().iterator();
while (itr.hasNext()) {
int[] foo = (int[]) itr.next();
...
}
…where lhm is a LinkedHashMap whose keys are arrays of ints.
Once we get to the cast, the following exception occurs:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(LinkedHashMap.java:390)
at java.util.LinkedHashMap$KeyIterator.next(LinkedHashMap.java:401)
So what am I doing wrong?
ETA: There is only one thread running, FWIW.
ticker
February 13, 2010, 9:43am
2
The iterators returned by the iterator method of the collections returned by all of this class’s collection view methods are fail-fast:** if the map is structurally modified at any time after the iterator is created**, in any way except through the iterator’s own remove method, 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.
My guess is that within your ‘while’ loop you are somehow messing with the map.
My guess? It’s in the line “…”.
Indistinguishable ’s law of debugging: it’s always in the part you were sure was irrelevant
Lobot
February 13, 2010, 9:53am
4
Bingo. I was conditionally removing elements. Once I used itr.remove(), it fixed itself.
Thanks!
Lobot
February 13, 2010, 9:54am
5
Your law is worth remembering…