You add an object to the list after starting the iterator. This will change the value of modCount in the inner class AbstractList $ Itr.class. next () of the iterator method will call the checkForComodification () method, which throws a ConcurrentModificationException. And this is called failure.
//add in abstractList public void add(int index, E element) { if (index<0 || index>size) throw new IndexOutOfBoundsException(); checkForComodification(); l.add(index+offset, element); expectedModCount = l.modCount; size++; modCount++; //modCount changed }
In AbstractList $ Itr
int expectedModCount; public E next() { checkForComodification(); // cause ConcurrentModificationException try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException(); } } private void checkForComodification() { if (l.modCount != expectedModCount) //modCount not equals to itr.expectedModCount throw new ConcurrentModificationException(); }
repeat this code after adding:
al.add(2, "inserted"); lir = al.iterator();
source share