JAVA集合异常java.util.ConcurrentModificationException

本文深入探讨了Java中集合在迭代过程中出现异常的原因,尤其是在使用ArrayList和迭代器时的常见错误。通过对比错误代码和修改后的代码,详细解释了如何避免ConcurrentModificationException异常,并提供了在遍历集合时正确删除元素的方法。

报异常的代码:

public class Demo01Iteractor {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
        Iterator<String> it = collection.iterator();
        collection.add("姚明");
        collection.add("詹姆斯");
//        System.out.println(collection);
        boolean b = it.hasNext();
        System.out.println(b);
        String s = it.next();//这里有异常
        System.out.println(s);
    }
}

修改后的代码:

public class Demo01Iteractor {
    public static void main(String[] args) {
        Collection<String> collection = new ArrayList<>();
        collection.add("姚明");
        collection.add("詹姆斯");
//        System.out.println(collection);
        Iterator<String> it = collection.iterator();
        boolean b = it.hasNext();
        System.out.println(b);
        String s = it.next();//这里有异常
        System.out.println(s);
    }
}

 

解决方法:只需要把创建迭代器对象的代码放在了add方法后面。

异常原因:

1.在集合内部有一个用于记录集合被修改的次数的变量a,每当集合内部结构发生变化(add,remove,set)时,a+1。

2.在迭代器内部也有一个当前集合修改的次数的变量b,初始化为集合中的a值。当我们在调用Iterator进行遍历操作时,a和b不相同,那么程序就会报异常。 上述错误代码就是犯了这个错误,b值初始为0,但是后面进行了add操作,a值增加,b值不变。所以遍历的时候产生了异常。

 

2020/7/4补充:在使用集合ArraList的时候当而且使用foreach遍历集合,这个时候使用remove(对象)的形式删除元素还是会报同一个异常。代码如下:

异常部分代码:

        for (Student student : studentList) {
            if (student.getStudentID().equals(stuID)){
                studentList.remove(student);
                System.out.println("删除成功");
            }
        }

解决方案:

       for (int i = 0; i < studentList.size(); i++) {
            if (studentList.get(i).getStudentID().equals(stuID)){
                studentList.remove(i);
                i--;
                System.out.println("删除成功");
            }
        }

结论:使用普通的正序遍历,按照索引删除即可,产生异常的原因和上面的原因相同,都是由于迭代器中标识数量的变量不一致导致的。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值