络腮胡菲菲 发表于 2024-3-19 04:52:52

Iterator集合底层原理

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

    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的四个细节


[*]NoSuchElementException异常
当上面循环结束之后,迭代器的指针已经指向了最后没有元素的位置
[*]迭代器遍历完成,指针不会复位
如果我们要继续第二次遍历集合,只能再次获取一个新的迭代器对象
[*]循环中只能用一次next方法
next方法的两件事情:获取元素,并移动指针
[*]迭代器遍历时,不能用集合的方法进行增加或者删除

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Iterator集合底层原理