File tree Expand file tree Collapse file tree 2 files changed +36
-3
lines changed
group17/102228177/src/data2_19 Expand file tree Collapse file tree 2 files changed +36
-3
lines changed Original file line number Diff line number Diff line change 1
1
package data2_19 ;
2
2
3
+ import java .util .ConcurrentModificationException ;
4
+ import java .util .NoSuchElementException ;
5
+
6
+
3
7
public class ArrayList implements List {
4
8
public static final int defLen = 10 ;
5
9
private Object [] elements ;
@@ -97,9 +101,32 @@ public int size(){
97
101
return size ;
98
102
}
99
103
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
+
103
130
public static void main (String [] args ) {
104
131
ArrayList list = new ArrayList ();
105
132
list .add (0 );
@@ -112,5 +139,10 @@ public static void main(String[] args) {
112
139
for (int i = 0 ; i < list .size (); i ++) {
113
140
System .out .println (i +":" +list .get (i ));
114
141
}
142
+
143
+ Iterator it = list .iterator ();
144
+ while (it .hasNext ()) {
145
+ System .out .println (it .next ());
146
+ }
115
147
}
116
148
}
Original file line number Diff line number Diff line change 1
1
package data2_19 ;
2
2
3
3
public interface List {
4
+
4
5
public void add (Object o );
5
6
public void add (int index , Object o );
6
7
public Object get (int index );
You can’t perform that action at this time.
0 commit comments