ToB企服应用市场:ToB评测及商务社交产业平台

标题: Iterator集合底层原理 [打印本页]

作者: 络腮胡菲菲    时间: 2024-3-19 04:52
标题: Iterator集合底层原理
  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的四个细节


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




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4