I was working on certain task, when incidentally did something wrong according to me but the code executed and provided correct result. I was little surpris
A for-each loop is possible for Classes that implement Iterable. This also means that you can create Classes yourself which you can use in for-each loops, which can be very comfortable.
This interface forces you to implement a method iterator()
which returns an Iterator
. Then the for-each loop does nothing but retrieve that iterator and iterate over it using hasNext()
and next()
. Just the same as you would do it yourself.
The problem with removing is that when you use a for-each loop and then remove an element from the List, the constructed Iterator
will not know anything about that change and there will be a ConcurrentModificationException
.
But if you call Iterator.remove()
directly, the Iterator will know about that change and can handle it.
A common little trick to avoid Iterators and Exceptions at the same time is to do something like this:
List
So you create a temporary copy of that List, iterate over that, but call remove on the original List.