Javaディエバソース解析
10706 ワード
1 private class Itr implements Iterator {
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 }