iterator
a menudo causan problemas, porque los desarrolladores a menudo no saben cómo funciona. El siguiente código es del código fuente de ArrayList
.
Un problema común es lanzar java.util.ConcurrentModificationException. Esta excepción es en realidad remove
método. remove()
tiene que ser llamado después next()
. si remove()
se llama antes next()
, el tamaño de la lista de arrays cambia, modCount != expectedModCount
se satisface y se lanza ConcurrentModificationException.
... public Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; } @SuppressWarnings("unchecked") public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new ConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; } public void remove() { if (lastRet < 0) throw new IllegalStateException(); checkForComodification(); try { ArrayList.this.remove(lastRet); cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } ... |