java - 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));
}
}
}
解决方案
不,此代码不会给出ConcurrentModificationException
. 当集合的视图被从其下方更改出来的集合“破坏”时,通常会发生该异常。Iterator
这方面的典型示例是在通过 a (在增强的 for 语句中隐式使用)或通过获取 a进行迭代时修改集合subList()
,修改基础列表,然后继续使用子列表。
但是,此代码将遇到与“破坏”循环相同的情况,除了将引发不同的异常。循环边界基于列表的初始大小。但是,循环体会从列表中删除元素,因此代码最终会在列表边界之外进行索引,从而导致IndexOutOfBoundsException
.
如何修复此代码取决于您要执行的操作。通过使用列表索引ConcurrentModificationException
而不是Iterator
. 但是,如果在循环过程中对列表进行结构修改(即添加或删除元素),则需要仔细调整索引和循环边界,否则可能会跳过、重复或IndexOutOfBoundsException
发生元素。
推荐阅读
- android - 我的应用主题(样式)中忽略了属性
- javascript - 我的 html 和 javascript 代码无法在 Safari 上运行
- tmux - 终端特定的 tmux 颜色
- ios - IOS 快捷方式:使用应用程序设置(嵌套)字典以修改 EXIF 数据
- haskell - 无法在终端中运行 ghci
- javascript - 如何匹配三种格式的日期
- seo - Sitemap file multilingual with dynamic content
- mysql - Mysql:带有数值的Order By显示错误的顺序
- c++ - OpenGL glm旋转
- laravel - Laravel 给了我一个重复的集合数据