我试图理解我必须在作业中回答的以下问题。它询问无限迭代器。他们会在哪里有用?我认为迭代器用于遍历像:
这样的集合Iterator itr = ArrayList.iterator();
while (itr.hasNext())
{
System.out.println(itr.next());
}
一旦itr
到达集合的末尾,就完成了,只要在迭代过程中不必进行其他操作。那么为什么要打扰无限的迭代器?
答案 0 :(得分:6)
无限迭代器完全按照上面的代码执行,除非它在到达结束元素时回退。
也许这个例子有助于说明它如何派上用场:
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] # 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