Iterator集合底层原理

打印 上一主题 下一主题

主题 917|帖子 917|积分 2751

  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方法的两件事情:获取元素,并移动指针
  • 迭代器遍历时,不能用集合的方法进行增加或者删除

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

络腮胡菲菲

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表