Skip to content

Commit 52cac43

Browse files
committed
Update 32.迭代器模式.md
1 parent 21f2656 commit 52cac43

File tree

1 file changed

+22
-6
lines changed

1 file changed

+22
-6
lines changed

32.迭代器模式.md

Lines changed: 22 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -19,21 +19,37 @@ public interface Iterable<T> {
1919
Iterator.java 实现
2020
```Java
2121
public interface Iterator<E> {
22-
boolean hasNext();
23-
E next();
22+
boolean hasNext();
23+
E next();
2424
}
2525
```
2626
ArrayList.java 实现 Iterable接口
2727
```Java
28-
@Override
29-
public Iterator<T> iterator() {
30-
return new ArrayListIterator();
28+
@Override
29+
public Iterator<T> iterator() {
30+
return new ArrayListIterator();
3131
}
3232
```
3333

3434
ArrayListIterator.java 实现
3535
```
36+
public class ArrayListIterator {
37+
int cursor;
38+
int lastRet = -1;
3639
40+
public boolean hasNext() {
41+
return cursor != size;
42+
}
43+
44+
public E next() {
45+
int i = cursor;
46+
if (i >= size)
47+
throw new NoSuchElementException();
48+
Object[] elementData = ArrayList.this.elementData;
49+
cursor = i + 1;
50+
return (E) elementData[lastRet = i];
51+
}
52+
}
3753
```
3854

39-
为了减少类文件和易于维护,我们通常把ArrayListIterator.java作为ArrayList的内部类,或者在ArrayList的iterator方法中世界采用匿名内部类,这里我们使用的内部类
55+
为了减少类文件和易于维护,我们通常把ArrayListIterator.java作为ArrayList的内部类,或者在ArrayList的iterator方法中世界采用匿名内部类,这里我们使用的外部类

0 commit comments

Comments
 (0)