- private class Itr implements Iterator<E> {
- int cursor; // 调用 next 方法返回的元素的索引
- int lastRet = -1; // 最近一次调用 next 方法返回的元素的索引 (如果没有调用过 next 方法, 这个值等于 - 1)
- int expectedModCount = modCount;
- Itr() {}
- /*
- * 判断光标指向的位置是否还有元素, 即迭代器下一次迭代是否还能获取到元素.
- */
- public boolean hasNext() {
- return cursor != size;
- }
- /*
- * 返回光标指向位置的元素, 然后移动光标.
- */
- @SuppressWarnings("unchecked")
- public E next() {
- checkForComodification();
- //1, 所以调用 next 方法前需要先调用 hasNext 方法进行判断 -- 避免抛出异常
- int i = cursor;
- if (i>= size)
- throw new NoSuchElementException();
- Object[] elementData = ArrayList.this.elementData;
- if (i>= elementData.length)
- throw new ConcurrentModificationException();
- //2, 先移动光标, 后返回数值
- cursor = i + 1;
- //3,lastRest 变量记录本次返回的元素在集合中的位置
- return (E) elementData[lastRet = i];
- }
- public void remove() {
- if (lastRet <0)
- throw new IllegalStateException();
- checkForComodification();
- try {
- //2, 从这里可以看出, remove 方法移除的是上一次调用 next 方法返回的元素.
- ArrayList.this.remove(lastRet);
- cursor = lastRet;
- //3, 从这里可以看出, remove 方法和 next 方法是紧密相关的.
- // 只有调用了 next 方法才能调用 remove 方法, remove 方法不能联系调用,
- // 下一次调用 remove 方法前必须调用 next 方法.
- lastRet = -1;
- expectedModCount = modCount;
- } catch (IndexOutOfBoundsException ex) {
- throw new ConcurrentModificationException();
- }
- }
- @Override
- @SuppressWarnings("unchecked")
- public void forEachRemaining(Consumer super E> consumer) {
- Objects.requireNonNull(consumer);
- final int size = ArrayList.this.size;
- int i = cursor;
- if (i>= size) {
- return;
- }
- final Object[] elementData = ArrayList.this.elementData;
- if (i>= elementData.length) {
- throw new ConcurrentModificationException();
- }
- 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();
- }
- final void checkForComodification() {
- if (modCount != expectedModCount)
- throw new ConcurrentModificationException();
- }
- }
来源: http://www.bubuko.com/infodetail-3321311.html