This is basically how the iterator works. This example uses List , but you can use an iterator for 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 }
To a large extent, you create an iterator instance by telling the collection to give you a link to its iterator. Then you loop through by typing hasNext() , which will keep you moving until you have more elements. Calling next() calls the next element from the iterator and increments its position by one. Calling remove() will remove the last element returned by next() (or previous() .) From the list.
Note that I used java.util.ListIterator instead of java.util.Iterator , since ListIterator is a special Iterator implementation optimized for use against lists, as in the example above.
You cannot use an iterator for an array. You will need to use vanilla for-loop or convert it to List or another object that implements Iterable .
To cycle through the list above, your loop will look something like this:
while(it.hasNext()) { String value = it.next(); // do processing if (!it.hasNext()) { it = someList.listIterator(); // reset the iterator } }
To cycle through an 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 } }
Alternatively, you can implement your Numbers class Numbers directly.
source share