当我们删除-1并清空ArrayList时,它会抛出ConcurrentModificationException,当我们从同一个空ArrayList中删除0时,它会抛出NoSuchElementException.
请找到以下代码:
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 "); } } }
从我的理解NoSuchElementException是好的,但为什么抛出ConcurrentModificationException?