Java ConcurrentModificationException

use*_*415 6 java exception

删除第二个最后一个元素时,没有ConcurrentModificationException

List<String> myList1 = new ArrayList<String>();
Collections.addAll(myList1, "str1","str2","str3","str4","str5");
for(String element : myList1){//no ConcurrentModificationException here
if(element.equalsIgnoreCase("str4"))
    myList1.remove("str4");
}
System.out.println(myList1);
Run Code Online (Sandbox Code Playgroud)

但是当删除其他元素时会出现ConcurrentModificationException

List<String> myList2 = new ArrayList<String>();
Collections.addAll(myList2, "str1","str2","str3","str4","str5");
for(String element : myList2){//ConcurrentModificationException here
if(element.equalsIgnoreCase("str1"))
    myList2.remove("str1");
}
System.out.println(myList2);
Run Code Online (Sandbox Code Playgroud)

是什么原因?

mre*_*mre 3

我也看到同样的事情

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Launcher 
{
    public static void main(String[] args) 
    {
        doThis();
        doThat();
    }

    private static void doThis()
    {
        System.out.println("dothis");
        try
        {
            List<String> myList1 = new ArrayList<String>();
            Collections.addAll(myList1, "str1","str2","str3","str4","str5");
            for(String element : myList1){//no ConcurrentModificationException here
            if(element.equalsIgnoreCase("str4"))
                myList1.remove("str4");
            }
            System.out.println(myList1);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    private static void doThat()
    {
        System.out.println("dothat");
        try
        {
            List<String> myList2 = new ArrayList<String>();
            Collections.addAll(myList2, "str1","str2","str3","str4","str5");
            for(String element : myList2){//ConcurrentModificationException here
            if(element.equalsIgnoreCase("str1"))
                myList2.remove("str1");
            }
            System.out.println(myList2);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

其输出,

dothis
[str1, str2, str3, str5]
dothat
java.util.ConcurrentModificationException
    at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
    at java.util.AbstractList$Itr.next(Unknown Source)
    at com.foo.Launcher.doThat(Launcher.java:41)
    at com.foo.Launcher.main(Launcher.java:12)
Run Code Online (Sandbox Code Playgroud)

我已经找到原因了。