Iterator集合底层原理

[复制链接]
发表于 2024-3-19 04:52:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
  1. //Itr是 ArrayList中的一个内部类
  2. private class Itr implements Iterator<E> {
  3.     int cursor;       // index of next element to return 光标,表示是迭代器里面的那个指针,默认指向0索引的位置
  4.     int lastRet = -1; // index of last element returned; -1 if no such 表示上一次操作的索引
  5.     int expectedModCount = modCount;
  6.     Itr() {}
  7.     public boolean hasNext() {
  8.         return cursor != size;
  9.     }
  10.     @SuppressWarnings("unchecked")
  11.     public E next() {
  12.         checkForComodification();
  13.         int i = cursor;
  14.         if (i >= size)
  15.             throw new NoSuchElementException();
  16.         Object[] elementData = ArrayList.this.elementData;
  17.         if (i >= elementData.length)
  18.             throw new ConcurrentModificationException();
  19.         cursor = i + 1;
  20.         return (E) elementData[lastRet = i];
  21.     }
  22.     public void remove() {
  23.         if (lastRet < 0)
  24.             throw new IllegalStateException();
  25.         checkForComodification();
  26.         try {
  27.             ArrayList.this.remove(lastRet);
  28.             cursor = lastRet;
  29.             lastRet = -1;
  30.             expectedModCount = modCount;
  31.         } catch (IndexOutOfBoundsException ex) {
  32.             throw new ConcurrentModificationException();
  33.         }
  34.     }
复制代码
iterator的四个细节


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

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表