- private class Itr implements Iterator<E> {
- int cursor; // 游标, 下一个要返回的元素的索引
- int lastRet = -1; // 返回最后一个元素的索引; 如果没有这样的话返回 - 1.
- int expectedModCount = modCount;
- // 通过 cursor != size 判断是否还有下一个元素
- 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];// 返回索引为 i 处的元素, 并将 lastRet 赋值为 i
- }
- public void remove() {
- if (lastRet <0)
- throw new IllegalStateException();
- checkForComodification();
- try {
- ArrayList.this.remove(lastRet);// 调用 ArrayList 的 remove 方法删除元素
- cursor = lastRet;// 游标指向删除元素的位置, 本来是 lastRet+1 的, 这里删除一个元素, 然后游标就不变了
- lastRet = -1;//lastRet 恢复默认值 - 1
- expectedModCount = modCount;//expectedModCount 值和 modCount 同步, 因为进行 add 和 remove 操作, modCount 会加 1
- } catch (IndexOutOfBoundsException ex) {
- throw new ConcurrentModificationException();
- }
- }
- @Override
- @SuppressWarnings("unchecked")
- public void forEachRemaining(Consumer<? super E> consumer) {// 便于进行 forEach 循环
- 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();
- }
- // 前面在新增元素 add() 和 删除元素 remove() 时, 我们可以看到 modCount++ 修改 set() 是没有的
- // 也就是说不能在迭代器进行元素迭代时进行增加和删除操作, 否则抛出异常
- final void checkForComodification() {
- if (modCount != expectedModCount)
- throw new ConcurrentModificationException();
- }
- }
来源: https://www.cnblogs.com/ysocean/p/8622264.html