Can someone please explain to me why do I get a ConcurrentModificationException
if I just want to access an element of the list?
I was under impression that ConcurrentModificationException
is thrown only when one thread iterates over a collection and another one tries to modify it. This is not my case though. I just want to get an element of the list.
Here is a code snippet which reproduces my problem (please don't judge the logic, I just wanted to reproduce the problem):
private static void checkConcurrentModificationException(){
List<String> stringSpan = new ArrayList<String>();
List<List<String>> clausesStrings = new ArrayList<List<String>>();
List<String> testStringList = new ArrayList<String>();
for (int i = 0; i < 121; i++) {
testStringList.add("abc");
}
for (int i = 0; i < testStringList.size(); i++) {
stringSpan.clear();
if (i%2==0) {
if (i>3) {
for (int j = i+1; j < testStringList.size(); j++) {
if (j>i+4 || j>=testStringList.size()-1) {
stringSpan = testStringList.subList(i, j); //might be the problem
clausesStrings.add(stringSpan);
break;
}
}
}
}
}
System.out.println("Clause list size: "+clausesStrings.size());
System.out.println("First clause: "+clausesStrings.get(0));
}
I analyzed the instructions and came to a conclusion that the problem lies in the stringSpan = testStringList.subList(i, j);
but I'm not quite sure what happens behind and why it fails. Also, I tried to copy(without reference) the resulting list of lists clausesStrings
to a new one but no luck so far.