Java ConcurrentModificationException

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.

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

Bingo. I was conditionally removing elements. Once I used itr.remove(), it fixed itself.

Thanks!

Your law is worth remembering…