Lets have a look at this example:
public class ListIteratorTest {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("element1");
list.add("element2");
list.add("element3");
list.add("element4");
ListIterator<String> iterator = list.listIterator();
}
}
And now, this works fine:
// prints elements out, and then appropriately removes one after another
while (iterator.hasNext()){
System.out.println(iterator.next());
iterator.remove();
}
while this throws an IllegalStateException:
// throws IllegalStateException, why?
iterator.forEachRemaining(n -> {
System.out.println(n);
iterator.remove();
});
My question is short: why?