Skip to content

Commit 3fdaf66

Browse files
committed
迭代器
1 parent e186438 commit 3fdaf66

File tree

2 files changed

+36
-3
lines changed

2 files changed

+36
-3
lines changed

group17/102228177/src/data2_19/ArrayList.java

Lines changed: 35 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
package data2_19;
22

3+
import java.util.ConcurrentModificationException;
4+
import java.util.NoSuchElementException;
5+
6+
37
public class ArrayList implements List{
48
public static final int defLen = 10;
59
private Object[] elements;
@@ -97,9 +101,32 @@ public int size(){
97101
return size;
98102
}
99103

100-
// public Iterator iterator(){
101-
// return null;
102-
// }
104+
public Iterator iterator(){
105+
return new ArrayListIterator();
106+
}
107+
108+
private class ArrayListIterator implements Iterator{
109+
int cursor;
110+
111+
@Override
112+
public boolean hasNext() {
113+
return cursor != size;
114+
}
115+
116+
@Override
117+
public Object next() {
118+
int i = cursor;
119+
if(i >= size){
120+
throw new NoSuchElementException();
121+
}
122+
if (i >= elements.length){
123+
throw new ConcurrentModificationException();
124+
}
125+
cursor = i+1;
126+
return elements[i];
127+
}
128+
}
129+
103130
public static void main(String[] args) {
104131
ArrayList list = new ArrayList();
105132
list.add(0);
@@ -112,5 +139,10 @@ public static void main(String[] args) {
112139
for (int i = 0; i < list.size(); i++) {
113140
System.out.println(i+":"+list.get(i));
114141
}
142+
143+
Iterator it = list.iterator();
144+
while (it.hasNext()) {
145+
System.out.println(it.next());
146+
}
115147
}
116148
}

group17/102228177/src/data2_19/List.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package data2_19;
22

33
public interface List {
4+
45
public void add(Object o);
56
public void add(int index, Object o);
67
public Object get(int index);

0 commit comments

Comments
 (0)