Iterator集合底层原理

发布时间 2024-01-04 10:34:52作者: 如夢初醒
//Itr是 ArrayList中的一个内部类
private class Itr implements Iterator<E> {
    int cursor;       // index of next element to return 光标,表示是迭代器里面的那个指针,默认指向0索引的位置
    int lastRet = -1; // index of last element returned; -1 if no such 表示上一次操作的索引
    int expectedModCount = modCount;

    Itr() {}

    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();
        }
    }

iterator的四个细节

  1. NoSuchElementException异常

    当上面循环结束之后,迭代器的指针已经指向了最后没有元素的位置

  2. 迭代器遍历完成,指针不会复位

    如果我们要继续第二次遍历集合,只能再次获取一个新的迭代器对象

  3. 循环中只能用一次next方法

    next方法的两件事情:获取元素,并移动指针

  4. 迭代器遍历时,不能用集合的方法进行增加或者删除