首页 > 解决方案 > Java - 使用经典for循环时会发生并发修改异常吗?

问题描述

使用经典 for 循环时是否有可能发生并发修改异常?

import java.util.*;

class IterTest{
    public static void main(String[] args){
        List<Integer> nums = new ArrayList<>();
        nums.add(18);
        nums.add(1);
        nums.add(14);
        nums.add(13);
        System.out.println("Nums ->"+nums);
        int len = nums.size();
        for(int index=0;index < len ;index++){          
            System.out.println(" Current >>"+nums.get(index));
            System.out.println(" Removing >>"+nums.remove(index));          
        }
    }
}

标签: javacollectionsexception-handlingfail-fast

解决方案


不,此代码不会给出ConcurrentModificationException. 当集合的视图被从其下方更改出来的集合“破坏”时,通常会发生该异常。Iterator这方面的典型示例是在通过 a (在增强的 for 语句中隐式使用)或通过获取 a进行迭代时修改集合subList(),修改基础列表,然后继续使用子列表。

但是,此代码将遇到与“破坏”循环相同的情况,除了将引发不同的异常。循环边界基于列表的初始大小。但是,循环体会从列表中删除元素,因此代码最终会在列表边界之外进行索引,从而导致IndexOutOfBoundsException.

如何修复此代码取决于您要执行的操作。通过使用列表索引ConcurrentModificationException而不是Iterator. 但是,如果在循环过程中对列表进行结构修改(即添加或删除元素),则需要仔细调整索引和循环边界,否则可能会跳过、重复或IndexOutOfBoundsException发生元素。


推荐阅读