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[]);

…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(
	at java.util.LinkedHashMap$

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.


Your law is worth remembering…