4

I am trying to understand the following question I have to answer in an assignment. It is asking about infinite iterators. Where they would be useful? I thought iterators are used to traverse through a collection like:

Iterator itr = ArrayList.iterator();
while (itr.hasNext())
{
    System.out.println(itr.next());
}

once itrreaches the end of the collection, it's done, as long as no other operations must been made in the middle of the iteration. So why even bother with infinite iterators?

Mysticial
  • 464,885
  • 45
  • 335
  • 332
Daniel
  • 53
  • 1
  • 6
  • 2
    http://stackoverflow.com/questions/2622591/is-an-infinite-iterator-bad-design This answers your question. – Vicky Mar 06 '12 at 06:07
  • 1
    Ah, I'm not sure which interpretation of "infinite iterator" is meant here. If the case is you need to iterate over an open ended range, then @NikunjChauhan is correct. If you mean an infinite iterator over a collection, like in the Google Collection libraries, PHP and a bunch of other languages then see below! – Ian Bishop Mar 06 '12 at 06:19

1 Answers1

6

An infinite iterator does exactly what your code above does except it rewinds when it hits the end elements.

Maybe this example will help illustrate how it might come in handy:

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++;
}

State of l at each iteration:

[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
Ian Bishop
  • 5,185
  • 3
  • 26
  • 37