java + ConcurrentModificationException forEach(增强)循环单线程 [英] java+ ConcurrentModificationException forEach(enhanced) loop single thread

查看:191
本文介绍了java + ConcurrentModificationException forEach(增强)循环单线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法理解原因,为什么下面的代码是抛出CME,即使这是作为单线程应用程序运行

I am not able to understand the reason, why the below code is throwing CME, even when this is run as single thread application

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

public class ConcurrentModification {

    public static void main(String[] args) {
        ConcurrentModification con = new ConcurrentModification();
        con.call();
    }

    void call() {
        List<Integer> l = new ArrayList<Integer>();
        for (int i = 0; i <= 10000; i++) {
            l.add(i);
        }

            for (Integer j : l) {
                if (j % 3 == 0) {
                    l.remove(j);
                }
            }


    }
}

原因:(通过答案和其他链接后)

Reason:(after going through the answer and other links)

You are not permitted to mutate a list while you are iterating over it.   
Only Iterator remove's method can be used to delete element from list  
For Each loop is using iterator beneath it  
but l.remove(j) is not using that iterator, which causes the exception 


推荐答案

您不允许在迭代时超过它。您的 l.remove(j)会导致列表 l 更改,但您位于 for(Integer j:l)循环。

You are not permitted to mutate a list while you are iterating over it. Your l.remove(j) causes the list l to change, but you're inside a for (Integer j : l) loop.

这篇关于java + ConcurrentModificationException forEach(增强)循环单线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆