I wrote two example code as following:
private static 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"));
l.add(new Person("d"));
for(int i = 0;i<l.size();i++)
{
Person s = l.get(i);
System.out.println(s.name);
if(s.name.equals("b"))
l.remove(i);
}
System.out.println("==========================");
for(Person s : l)
System.out.println(s.name);
}
When I run example code, print on console following result:
a
b
d
==========================
a
c
d
but when I change code as following by a iterate model:
int i = 0;
for(Person s : l)
{
if(s.name.equals("b"))
l.remove(i);
i++;
}
I get following result:
a
b
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
Means of examples are: In traditional loop model ConcurrentModificationException not occurred at traditional for model??