迭代器 (Iterator)

迭代器(Iterator)

提供按顺序访问聚合对象的元素,并不暴露聚合对象的内部表示。

java 代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public interface Iterator<T> {

boolean hasNext();

T next();
}


public class ConcreteIterator<Item> implements Iterator<Item> {

private Item[] items;
private int position = 0;

public ConcreteIterator(Item[] items) {
this.items = items;
}

@Override
public boolean hasNext() {
return position < items.length;
}

@Override
public Item next() {
return items[position++];
}
}

public class IteratorTest {

public static void main(String[] args) {
Integer[] items = new Integer[10];
for (int i = 0; i < items.length; i++) {
items[i] = i;
}
Iterator<Integer> iterator = new ConcreteIterator<>(items);
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}