关于java:什么是无限迭代器?

What is an Infinite Iterator? Why use it?

我试图理解我在作业中必须回答的以下问题。它询问无限迭代器。它们在哪里有用?我认为迭代器用于遍历集合,比如:

1
2
3
4
5
Iterator itr = ArrayList.iterator();
while (itr.hasNext())
{
    System.out.println(itr.next());
}

一旦itr到达集合的末尾,就完成了,只要在迭代过程中不需要进行其他操作。那么,为什么还要考虑无限迭代器呢?


无限迭代器和上面的代码完全一样,只不过当它碰到结束元素时会倒带。

也许这个例子有助于说明它是如何变得有用的:

1
2
3
4
5
6
7
8
9
10
Let l = [1,2,3,4,5,6,7,8]

int i = 0;
InfiniteIterator itr = l.infiniteIterator();
while(itr.hasNext()) {
    if(i % 2 == 0) {
        itr.remove();
    }
    i++;
}

每次迭代时l的状态:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[1,2,3,4,5,6,7,8] # i = 0, e = 1
[2,3,4,5,6,7,8] # i = 1, e = 2
[2,3,4,5,6,7,8] # i = 2, e = 3
[2,4,5,6,7,8] # i = 3, e = 4
[2,4,5,6,7,8] # i = 4, e = 5
[2,4,6,7,8] # i = 5, e = 6
[2,4,6,7,8] # i = 6, e = 7
[2,4,6,8] # i = 7, e = 8
[2,4,6,8] # i = 8, e = 2
[4,6,8] # i = 9, e = 4
[4,6,8] # i = 10, e = 6
[4,8] # i = 11, e = 8
[4,8] # i = 12, e = 4
[8] # i = 13, e = 8
[8] # i = 14, e = 8
[] # while loop exits