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. Callingit.hasNext()does not throw aConcurrentModificationExceptionbut 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.http://ideone.com/VKhHWN