回答編集履歴

1

追記

2019/08/08 08:41

投稿

退会済みユーザー
test CHANGED
@@ -11,3 +11,141 @@
11
11
  この例外は、オブジェクトの並行変更を検出したメソッドによって、そのような変更が許可されていない場合にスローされます。
12
12
 
13
13
  ```
14
+
15
+
16
+
17
+ ### ArrayList$Itr の実装
18
+
19
+ ```
20
+
21
+ private class Itr implements Iterator<E> {
22
+
23
+ int cursor; // index of next element to return
24
+
25
+ int lastRet = -1; // index of last element returned; -1 if no such
26
+
27
+ int expectedModCount = modCount;
28
+
29
+
30
+
31
+ // prevent creating a synthetic constructor
32
+
33
+ Itr() {}
34
+
35
+
36
+
37
+ public boolean hasNext() {
38
+
39
+ return cursor != size;
40
+
41
+ }
42
+
43
+
44
+
45
+ @SuppressWarnings("unchecked")
46
+
47
+ public E next() {
48
+
49
+ checkForComodification();
50
+
51
+ int i = cursor;
52
+
53
+ if (i >= size)
54
+
55
+ throw new NoSuchElementException();
56
+
57
+ Object[] elementData = ArrayList.this.elementData;
58
+
59
+ if (i >= elementData.length)
60
+
61
+ throw new ConcurrentModificationException();
62
+
63
+ cursor = i + 1;
64
+
65
+ return (E) elementData[lastRet = i];
66
+
67
+ }
68
+
69
+
70
+
71
+ public void remove() {
72
+
73
+ if (lastRet < 0)
74
+
75
+ throw new IllegalStateException();
76
+
77
+ checkForComodification();
78
+
79
+
80
+
81
+ try {
82
+
83
+ ArrayList.this.remove(lastRet);
84
+
85
+ cursor = lastRet;
86
+
87
+ lastRet = -1;
88
+
89
+ expectedModCount = modCount;
90
+
91
+ } catch (IndexOutOfBoundsException ex) {
92
+
93
+ throw new ConcurrentModificationException();
94
+
95
+ }
96
+
97
+ }
98
+
99
+
100
+
101
+ @Override
102
+
103
+ public void forEachRemaining(Consumer<? super E> action) {
104
+
105
+ Objects.requireNonNull(action);
106
+
107
+ final int size = ArrayList.this.size;
108
+
109
+ int i = cursor;
110
+
111
+ if (i < size) {
112
+
113
+ final Object[] es = elementData;
114
+
115
+ if (i >= es.length)
116
+
117
+ throw new ConcurrentModificationException();
118
+
119
+ for (; i < size && modCount == expectedModCount; i++)
120
+
121
+ action.accept(elementAt(es, i));
122
+
123
+ // update once at end to reduce heap write traffic
124
+
125
+ cursor = i;
126
+
127
+ lastRet = i - 1;
128
+
129
+ checkForComodification();
130
+
131
+ }
132
+
133
+ }
134
+
135
+
136
+
137
+ final void checkForComodification() {
138
+
139
+ if (modCount != expectedModCount)
140
+
141
+ throw new ConcurrentModificationException();
142
+
143
+ }
144
+
145
+ }
146
+
147
+ ```
148
+
149
+
150
+
151
+ つまり Iterator が作成されたときと 処理を実行したときに違いがあればエラーとなる。