我按照一个测试ConcurrentModificationException
的概念编写了这个例子:
public class Person
{
String name;
public Person(String name)
{
this.name = name;
}
}
public static void main(String[] args)
{
List<Person> l = new ArrayList<Person>();
l.add(new Person("a"));
l.add(new Person("b"));
l.add(new Person("c"));
int i = 0;
for(Person s : l)
{
if(s.name.equals("b"))
l.remove(i);
i++;
}
for(Person s : l)
System.out.println(s.name);
}
当我执行上述的main方法时,没有抛出ConcurrentModificationException异常,控制台输出以下结果:
a
c
根据我的了解,当在列表的循环中修改列表时,应该抛出ConcurrentModificationException
异常。但是为什么在我的示例中没有发生这种情况呢?
remove
后立即退出,如果在 "c" 之后添加第4个元素或删除 Person "a" ,则会导致异常。 - Marvin