为什么我不能在一个相等列表的同一方法中有 2 个循环? JAVA

Why can not I have 2 loops in the same method on an equal list? JAVA

我在考java8认证,发现了一件不得了的事!

我正在上一门课程,在解释 Java 中的 List 时,他谈到了 ConcurrentModificationException

看看这个片段:

List<String> lista = new LinkedList<>();

lista.add("d");
lista.add("d");
lista.add("d");
lista.add("d");

for(int i = 0; i<lista.size(); i++){
    System.out.println(lista.get(i));

}

for(String s : lista){
    lista.add(s);
}}

为什么 java 没有 ITERATOR 抛出 ConcurrentModificationException

难道不应该从第一个循环开始读取列表,只有在第一个循环结束后才从第二个循环开始吗?

如何在第一个循环仍在迭代时执行第二个循环?

for (Element e: list) 构造在内部使用 Iterator<Element>,它解释了您的 ConcurrentModificationException

参见 here 例如:

The compiler does [create the Iterator] for you behind your back, but you need not concern yourself with it.*

--> 如果您打算在迭代结构时修改结构,您实际上确实需要关心它。

*为了清楚起见,我将方括号之间的内容替换掉了。

第二个问题是您正在添加新元素。然而在第一个你只是阅读。

想象一下,你一直在数书,有人在中间插书。有多烦人?不插入新书,无论读多少遍,结果都不会改变。