Iterator.remove() IllegalStateException
@rgettman answer is correct but to give you imagination.
Our collection: |el1| |el2| |el3|
when you call iterator.next()
it works this way:
|el1| iterator |el2| |el3|
so it jumps over the element and return reference to the element which was jumped (|el1|). So if we called iterator.remove()
now, |el1| would be removed.
It's worth to add what @PedroBarros mentioned above - you can't call iterator.remove()
two times without iterator.next()
between them because IllegalStateException
would be thrown.
Also when you create two iterators (iterator1, iterator2) then calling:
iterator1.next();
iterator1.remove();
iterator2.next();
will throw ConcurrentModificationException because iterator2
checks that collection was modified.
You haven't called next()
on your Iterator
, so it's not referring to the first item yet. You can't remove the item that isn't specified yet.
Call next()
to advance to the first item first, then call remove()
.
It will also call this exeption, If you add something to the list in iterator and then after it not calling it.next()
again but removing the item