What is an infinite iterator? Why use it?

I am trying to understand the following question that I must answer in the assignment. He asks about endless iterators. Where would they be helpful? I thought iterators are used to go through the collection, for example:

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

since itr reaches the end of the collection, this is done until no other operations are performed in the middle of the iteration. So why bother with endless iterators?

+4
source share
1 answer

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

Perhaps this example will help illustrate how this 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 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 
+6
source

Source: https://habr.com/ru/post/1399931/


All Articles