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