小编use*_*108的帖子

foreach循环中的ConcurrentModificationException

在我的代码中:

    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循环之前对我的集合进行了更改.

java collections arraylist concurrentmodification

0
推荐指数
1
解决办法
6224
查看次数