Java迭代器源码解析

 1  private class Itr implements Iterator<E> {
 2         int cursor;       // 调用next方法返回的元素的索引
 3         int lastRet = -1; // 最近一次调用next方法返回的元素的索引(如果没有调用过next方法,这个值等于-1)
 4         int expectedModCount = modCount;
 5 
 6         Itr() {}
 7 
 8         /*
 9         *判断光标指向的位置是否还有元素,即迭代器下一次迭代是否还能获取到元素。
10         */
11         public boolean hasNext() {
12             return cursor != size;
13         }
14 
15         /*
16         *返回光标指向位置的元素,然后移动光标。
17         */
18         @SuppressWarnings("unchecked")
19         public E next() {
20             checkForComodification();
21             //1、所以调用next方法前需要先调用hasNext方法进行判断——避免抛出异常
22             int i = cursor;
23             if (i >= size)
24                 throw new NoSuchElementException();
25             Object[] elementData = ArrayList.this.elementData;
26             if (i >= elementData.length)
27                 throw new ConcurrentModificationException();
28             //2、先移动光标,后返回数值
29             cursor = i + 1;
30             //3、lastRest变量记录本次返回的元素在集合中的位置
31             return (E) elementData[lastRet = i];
32         }
33 
34         public void remove() {
35             if (lastRet < 0)
36                 throw new IllegalStateException();
37             checkForComodification();
38 
39             try {
40                 //2、从这里可以看出,remove方法移除的是上一次调用next方法返回的元素。
41                 ArrayList.this.remove(lastRet);
42                 cursor = lastRet;
43                 //3、从这里可以看出,remove方法和next方法是紧密相关的。
44                 //只有调用了next方法才能调用remove方法,remove方法不能联系调用,
45                 //下一次调用remove方法前必须调用next方法。
46                 lastRet = -1;
47                 expectedModCount = modCount;
48             } catch (IndexOutOfBoundsException ex) {
49                 throw new ConcurrentModificationException();
50             }
51         }
52 
53         @Override
54         @SuppressWarnings("unchecked")
55         public void forEachRemaining(Consumer<? super E> consumer) {
56             Objects.requireNonNull(consumer);
57             final int size = ArrayList.this.size;
58             int i = cursor;
59             if (i >= size) {
60                 return;
61             }
62             final Object[] elementData = ArrayList.this.elementData;
63             if (i >= elementData.length) {
64                 throw new ConcurrentModificationException();
65             }
66             while (i != size && modCount == expectedModCount) {
67                 consumer.accept((E) elementData[i++]);
68             }
69             // update once at end of iteration to reduce heap write traffic
70             cursor = i;
71             lastRet = i - 1;
72             checkForComodification();
73         }
74 
75         final void checkForComodification() {
76             if (modCount != expectedModCount)
77                 throw new ConcurrentModificationException();
78         }
79     }

猜你喜欢

转载自www.cnblogs.com/KenBaiCaiDeMiao/p/12003380.html