我们在使用迭代器Iterator遍历集合中元素的过程中修改集合中元素的操作会抛出一个并发修改异常: ConcurrentModificationException, 这里以debug模式查看其代码执行过程是怎么触发这个异常的。
首先先来看一下代码:
public class ListDemo2 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
//添加一个元素
list.add("hello");
// list.add("world");
// list.add("java");
// list.add("python");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("hello")) {
list.remove("hello");
}
}
System.out.println(list);
}
}
案例源码追踪过程:
在代码中,先添加一个元素,然后使用迭代器遍历的过程中,对list中元素进行删除,此时看看debug模式代码如何执行。