File tree Expand file tree Collapse file tree 2 files changed +74
-0
lines changed
junit/com/ikook/basic_data_structure
src/com/ikook/basic_data_structure Expand file tree Collapse file tree 2 files changed +74
-0
lines changed Original file line number Diff line number Diff line change @@ -51,6 +51,7 @@ public void testIsEmpty() {
51
51
52
52
@ Test
53
53
public void testGet () {
54
+ assertEquals ("111" , list .get (0 ));
54
55
assertEquals (new Date (), list .get (4 ));
55
56
}
56
57
@@ -71,5 +72,21 @@ public void testSet() {
71
72
assertEquals (33 , list .set (2 , "333" ));
72
73
assertEquals ("333" , list .get (2 ));
73
74
}
75
+
76
+ @ Test
77
+ public void testIterator () {
78
+ int i = 0 ;
79
+ for (MyIterator iter = list .iterator (); iter .hesNext ();) {
80
+ Object str = (Object ) iter .next ();
81
+ assertEquals (list .get (i ++), str );
82
+ }
83
+
84
+ int j = list .size ();
85
+ for (MyIterator iter = list .iterator (); iter .hesNext ();) {
86
+ iter .next ();
87
+ iter .remove ();
88
+ assertEquals ( --j , list .size ());
89
+ }
90
+ }
74
91
75
92
}
Original file line number Diff line number Diff line change 1
1
package com .ikook .basic_data_structure ;
2
2
3
+ import java .util .ConcurrentModificationException ;
4
+ import java .util .NoSuchElementException ;
5
+
3
6
/**
4
7
* @author ikook; QQ号码: 935542673
5
8
*/
@@ -155,4 +158,58 @@ private void rangeCheck(int index) {
155
158
}
156
159
}
157
160
}
161
+
162
+ /**
163
+ * 返回一个迭代器的实现
164
+ * @return
165
+ */
166
+ public MyIterator iterator () {
167
+ return new Iter ();
168
+ }
169
+
170
+ /**
171
+ * 迭代器的实现类
172
+ * @author ikook
173
+ */
174
+ private class Iter implements MyIterator {
175
+
176
+ int cursor ; // 返回下一个元素的索引
177
+ int lastRet = -1 ; // 返回最后一个元素的索引(始终指向刚遍历完的元素),如果没有元素了,则为 -1
178
+
179
+ @ Override
180
+ public boolean hesNext () {
181
+ return cursor != size ; // cursor 等于 size 则集合遍历完。
182
+ }
183
+
184
+ @ Override
185
+ public Object next () {
186
+
187
+ try {
188
+ int i = cursor ;
189
+ Object next = get (i );
190
+ lastRet = i ;
191
+ cursor = i + 1 ;
192
+ return next ;
193
+ } catch (IndexOutOfBoundsException e ) {
194
+ throw new NoSuchElementException ("没有找到指定的元素, 迭代器遍历失败" );
195
+ }
196
+
197
+ }
198
+
199
+ @ Override
200
+ public void remove () {
201
+ if (lastRet < 0 ) {
202
+ throw new IllegalStateException ("非法状态异常,删除失败" );
203
+ }
204
+
205
+ try {
206
+ MyArrayList .this .remove (lastRet );
207
+ cursor = lastRet ;
208
+ lastRet = -1 ;
209
+ } catch (IndexOutOfBoundsException e ) {
210
+ throw new ConcurrentModificationException ("竞争者改变异常,删除失败" );
211
+ }
212
+ }
213
+
214
+ }
158
215
}
You can’t perform that action at this time.
0 commit comments