I was reading about ConcurrentModificationException and how to avoid it. Found an article. The first listing in that article had code similar to the following, which would apparently cause the exception:
List<String> myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");
Iterator<String> it = myList.iterator();
while(it.hasNext())
{
String item = it.next();
if("February".equals(item))
{
myList.remove(item);
}
}
for (String item : myList)
{
System.out.println(item);
}
Then it went on to explain how to solve the problem with various suggestions.
When I tried to reproduce it, I didn't get the exception! Why am I not getting the exception?
According to the Java API docs Iterator.hasNext does not throw a ConcurrentModificationException
.
After checking "January"
and "February"
you remove one element from the list. Calling it.hasNext()
does not throw a ConcurrentModificationException
but returns false. Thus your code exits cleanly. The last String however is never checked. If you add "April"
to the list you get the Exception as expected.
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String args[]) {
List<String> myList = new ArrayList<String>();
myList.add("January");
myList.add("February");
myList.add("March");
myList.add("April");
Iterator<String> it = myList.iterator();
while(it.hasNext())
{
String item = it.next();
System.out.println("Checking: " + item);
if("February".equals(item))
{
myList.remove(item);
}
}
for (String item : myList)
{
System.out.println(item);
}
}
}