The syntax for each is for collections ( Iterable , to be precise), and not for iterators. I am trying to figure out the arguments why Java was created this way in this question .
The simplest solution for you would be to return a reverse list (which is iterable) instead of a list iterator. Then you can use the shorthand loop syntax.
In the question mentioned earlier , the hacker path is described using the Adapter class, which wraps Iterator as Iterable and returns Iterator on the first call to iterator() . Look at the adapter code, it is quite simple. It serves the purpose, but since an iterator can only be used once, it is somewhat invalid Iterable (it will not be able to create a second iterator).
A key difference in behavior appears when you use it twice:
for(Object a : foo) { } for(Object a : foo) { }
will process all elements in foo twice if it is Iterable correct, but only once if it uses the adapter I painted - the second loop will do nothing.
Anony-Mousse Jun 26 '12 at 23:20 2012-06-26 23:20
source share