When we remove -1 from and empty ArrayList it throws ConcurrentModificationException and when we remove 0 from same empty ArrayList it throws NoSuchElementException.
Please find the code below :
public class Test {
public static void main(String[] argv) {
ArrayList<Integer> list = new ArrayList<Integer>();
Iterator<Integer> it = list.iterator();
try {
list.remove(-1);
} catch (IndexOutOfBoundsException e) {
}
try {
it.next();// Throwing ConcurrentModificationException
} catch (ConcurrentModificationException e) {
System.err.println("ConcurrentModificationException 1");
} catch (NoSuchElementException e) {
System.err.println("NoSuchElementException 1 ");
}
list = new ArrayList<Integer>();
it = list.iterator();
try {
list.remove(0);
} catch (IndexOutOfBoundsException e) {
}
try {
it.next();// Throwing NoSuchElementException
} catch (NoSuchElementException e) {
System.err.println("NoSuchElementException 2");
} catch (ConcurrentModificationException e) {
System.err.println("ConcurrentModificationException 2 ");
}
}
}
From my understanding NoSuchElementException is fine but why ConcurrentModificationException is thrown ?