ArrayList源码分析-迭代器

153 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第9天,点击查看活动详情

ArrayList源码分析-迭代器

迭代器内部参数:

    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;
        ......
    }
  1. int cursor 迭代过程中,下一个元素的位置,默认从 0 开始。
  2. int lastRet = -1 新增时表示上一次迭代过程中,索引的位置;删除时表示为 -1。
  3. int expectedModCount = modCount· expectedModCount 表示迭代过程中,期望的版本号
  4. modCount 表示数组的版本号。

迭代器主要方法:

hasNext():

        public boolean hasNext() {
            return cursor != size;
        }
  1. 此方法主要用于判断还有没有值可以迭代
  2. cursor != size; 首先cursor 表示下一个元素的位置,size 表示实际大小,如果相等的话,说明没有元素可以进行继续迭代了,如果不相等,则说明可以继续迭代

next():

        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];
        }

        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }        
  1. 此方法主要表示如果有值可以迭代,迭代的值是多少
  2. checkForComodification(); 表示迭代过程中,判断版本号有无被修改,有被修改,抛 ConcurrentModificationException 异常
  3. int i = cursor; 表示本次迭代过程中,元素的索引位置
  4. cursor = i + 1; 表示下一次迭代时,元素的位置,为下一次迭代做准备
  5. checkForComodification()表示版本号比较

remove():

        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();
            }
        }
  1. 此方法主要删除当前迭代的值
  2. if (lastRet < 0) 先判断上一次操作时,数组的位置是否已经小于 0 ,如果是的话,则数组已经被全部删除
  3. checkForComodification(); 迭代过程中,判断版本号有无被修改,有被修改,抛 ConcurrentModificationException 异常
  4. lastRet = -1; -1 表示元素已经被删除,也防止重复删除
  5. expectedModCount = modCount; 删除元素时 modCount 的值已经变化,赋值给 expectedModCount,下次迭代时,两者的值是一致的了