publicstaticvoidmain(String[] args) { MyIteratormi=newMyIterator(); while (mi.hasNext()){ System.out.printf("%s\t",mi.next()); } } }
classMyIteratorimplementsIterator<String>{ private String[] words = ("And that is how " + "we know the Earth to be banana-shaped.").split(" "); privateintcount=0;
@SuppressWarnings("unchecked") public E next() { checkForComodification(); //检测集合元素是否执行添加删除操作 inti= cursor; if (i >= size) thrownewNoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) thrownewConcurrentModificationException(); cursor = i + 1; return (E) elementData[lastRet = i]; }
publicvoidremove() { if (lastRet < 0) thrownewIllegalStateException(); checkForComodification();
@Override @SuppressWarnings("unchecked") publicvoidforEachRemaining(Consumer<? super E> consumer) { Objects.requireNonNull(consumer); finalintsize= ArrayList.this.size; inti= cursor; if (i >= size) { return; } final Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) { thrownewConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { consumer.accept((E) elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } //如果发生添加删除操作,则抛出错误。 finalvoidcheckForComodification() { if (modCount != expectedModCount) thrownewConcurrentModificationException(); } }
The number of times this list has been structurally modified. Structural modifications are those that change the size of the list, or otherwise perturb it in such a fashion that iterations in progress may yield incorrect results.