天天看点

java.util.ConcurrentModificationException 异常

public static void main(String[] args) {
        ArrayList<String> aList = new ArrayList<String>();
        aList.add("bbc");
        aList.add("abc");
        aList.add("ysc");
        aList.add("saa");
        System.out.println("移除前:" + aList);

        Iterator<String> it = aList.iterator();
        while (it.hasNext()) {
            if ("abc".equals(it.next())) {
                aList.remove("abc");
            }
        }
        System.out.println("移除后:" + aList);
    }
           

来看看,这段代码为什么会抛出 “java.util.ConcurrentModificationException” 异常,为了防止元素出现不可预期的结果,为什么会出现不可以预期的结果:

在Java中,迭代器是采用游标方式来访问集合中元素的:

1 2 3 4
a b c d e

当迭代器访问到cursor=3,元素:d时,此时元素下标cursor=cursor+1, 其值=4,这时候出现删除操作, list.remove(3); 集合变成如下形式:

1 2 3 4
a b c e null

此时调用next()方法,返回cursor=4, 指向的元素,其值为null, 不符合期望值e, 所以java中需要避免这种不可预期的结果出现。所以就会抛出java.util.ConcurrentModificationException?

至于如何实现,请参考JDK源码

上述代码正确删除方法,采用迭代器来删除

public static void main(String[] args) {
        ArrayList<String> aList = new ArrayList<String>();
        aList.add("bbc");
        aList.add("abc");
        aList.add("ysc");
        aList.add("saa");
        System.out.println("移除前:" + aList);

        Iterator<String> it = aList.iterator();
        while (it.hasNext()) {
            if ("abc".equals(it.next())) {
                it.remove();
            }
        }
        System.out.println("移除后:" + aList);
    }
           

继续阅读