Skip to content

Commit b273a57

Browse files
committed
ArrayList(The madman implementation)
添加了 Iterator 实现类以及 Iterator 实现类的测试用例
1 parent 1677a2d commit b273a57

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

group18/935542673/Coding/junit/com/ikook/basic_data_structure/MyArrayListTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ public void testIsEmpty() {
5151

5252
@Test
5353
public void testGet() {
54+
assertEquals("111", list.get(0));
5455
assertEquals(new Date(), list.get(4));
5556
}
5657

@@ -71,5 +72,21 @@ public void testSet() {
7172
assertEquals(33, list.set(2, "333"));
7273
assertEquals("333", list.get(2));
7374
}
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+
}
7491

7592
}

group18/935542673/Coding/src/com/ikook/basic_data_structure/MyArrayList.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
package com.ikook.basic_data_structure;
22

3+
import java.util.ConcurrentModificationException;
4+
import java.util.NoSuchElementException;
5+
36
/**
47
* @author ikook; QQ号码: 935542673
58
*/
@@ -155,4 +158,58 @@ private void rangeCheck(int index) {
155158
}
156159
}
157160
}
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+
}
158215
}

0 commit comments

Comments
 (0)