August 11, 2011

Can you remove an element from a collection while iterating over it? Answer: No, you can’t.

What kind of error will you get in Java if you make an attempt? Compile time or Runtime? Answer: Runtime.

The details of the exception will be as below. Check this along with a sample program that I wrote. You can try to compile and run it yourself to see the result.

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
at java.util.AbstractList$Itr.next(AbstractList.java:420)