1

I have this peace of code.
I know that this must give me ConcurrentModificationException
and i must use iterator or clone the list or just use for loop.

The problem is that this code runs without problem and ls.remove works at any index between 0-2.
Now if i change s.equals("two") to s.equals("one") OR anything else from list except "two"
I will always get ConcurrentModificationException as expected.

Also if i uncomment the ls.add("four") line ,i will always have ConcurrentModificationException no matter what the s.equals() be.

And my questions is why this is happening and why the code below run fine whithout ConcurrentModificationException only for s.equals("two") ?

import java.util.*;
import java.util.List;

    public class Test {

    public static void main(String args[]) {

        List<String> ls = new ArrayList<>();

        ls.add("one");
        ls.add("two");
        ls.add("three");
        //ls.add("four");

        for(String s : ls) {
            if(s.equals("two")) {
                ls.remove(0);
                //ls.remove("three");
            }
        }

        System.out.println(ls.size());

    }

}

and the output

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at Test.main(Test.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at     sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.    java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)

1 Answers1

1

You must not modify a list while iterating over it. An iterator may (or may not) fail, depending on the implementation. So removing some elements in part of the list may work, others may not. The save way to circumvent this issue is to use the iterators remove method, or to use a CopyOnWriteArrayList or any other collection supporting this kind of modification.

loonytune
  • 1,775
  • 11
  • 22