foreach循环中的ConcurrentModificationException

use*_*108 0 java collections arraylist concurrentmodification

在我的代码中:

    Collection<String> c = new ArrayList<>();
    Iterator<String> it = c.iterator();
    c.add("Hello");
    System.out.println(it.next());
Run Code Online (Sandbox Code Playgroud)

发生异常,因为我的集合在创建迭代器后发生了变化.

但是在这段代码中呢:

 ArrayList<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(2);
    list.add(3);
    for (Integer integer : list) {     // Exception is here
        if (integer.equals(2)) {
            list.remove(integer);
        }
    }
Run Code Online (Sandbox Code Playgroud)

为什么发生例外?

在第二个代码中,我在for-each循环之前对我的集合进行了更改.

Mar*_*nov 5

在第二个循环中,原因相同 - 您要从列表中删除元素.

要从List循环中删除元素,请使用标准的老式for循环:

for(int i=0;i<list.size();i++) {
Run Code Online (Sandbox Code Playgroud)

并删除该循环内的列表项或使用a ListIterator迭代列表.