I wrote this example following a test ConcurrentModificationException
concept:
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);
}
When I executed the above main method, ConcurrentModificationException
doesn't get thrown and the output console prints the following result:
a
c
By with my knowledge of this issue, when in a loop for list, when modifying the list,a ConcurrentModificationException
exception should be thrown. But why in my sample does this not occur?
There is no guarantee that structural modifications to the list will throw a
ConcurrentModificationException
.From the documentation:
In this particular case, you're "lucky" (or "unlucky" depending on how you see it). The structural change goes unnoticed since the loop exists before another modification check is performed.
For a detailed explanation, refer to the answers in the dup: