This is basically how an iterator works. This example uses a List
, but you can use an iterator against any collection that implements java.lang.Iterable
.
List<String> someList; // assume this has been instantiated and has values in it
ListIterator<String> it = someList.listIterator();
while (it.hasNext()) {
String value = it.next();
// do something with value
}
Pretty much, you instantiate the iterator by telling the collection to give you a reference to its iterator. Then you loop by calling hasNext()
, which will keep you going until you have no more elements. The call to next()
pulls the next item from the iterator and increments its position by one. A call to remove()
will remove from the list the last item returned by next()
(or previous()
.)
Note, of course, that I've been using java.util.ListIterator
instead of java.util.Iterator
because the ListIterator
is a special implementation of Iterator
optimized for use against lists, like in the example I gave above.
You cannot use an iterator against an array. You'd need to use a vanilla for-loop or convert it into a List
or another object that implements Iterable
.
To loop through the above list endlessly, your loop would look something like this:
while(it.hasNext()) {
String value = it.next();
// do processing
if (!it.hasNext()) {
it = someList.listIterator(); // reset the iterator
}
}
To loop through the array using a for-loop endlessly:
for (int i = 0; i < myArray.length; i++) {
myArray[i];
// do something
if (i == myArray.length - 1) {
i = 0; // reset the index
}
}
Alteratively you could have your Numbers
class implement Iterable
directly.