Background
Given an ArrayList of Integers from 0 (inclusive) to 10 (exclusive) with
step size 1. We use a while-loop and an Iterator<Integer> to check if
this ArrayList hasNext() element, before we remove() the current element.
Problem
The code below throws an IllegalStateException.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class UnderstandArrayListIterator {
public static void main(String[] args) {
List<Integer> a = new ArrayList<>();
for (int i = 0; i < 10; i++) {
a.add(i);
}
Iterator<Integer> iter = a.iterator();
iter.next();
while (iter.hasNext()) {
iter.remove();
}
}
}
Discussion
After invoking remove(), lastRet is set to -1, so
next time that this method is invoked, the condition lastRet < 0 in the
if-block is satisfied, resulting in an IllegalStateException.