For simple loops over arrays, you will not (usually) use Iterator in Java.
for(int i=0;i < arrayOfInts.length ; i+2){ System.out.println(arrayOfInts[i])); }
The idea of an iterator is to separate how the data is stored (maybe not an array) from its consumer (code that wants to iterate over it).
You have the right to say that Iterator is a fairly basic concept in the Java class library, so widespread that from Java5 there is a function for each cycle that supports it. In this loop, the user no longer sees Iterator.
for(Something element: listOfSomething){ System.out.println(element); }
If I were to implement a “smooth stepping iterator”, I would base it on a regular iterator so that it can be used with any iterable.
public class EvenSteppingIterator<X> implements Iterator<X>{ private final Iterator<X> source; public EvenSteppingIterator(Iterator<X> source){ this.source = source; // skip the first one, start from the second if (source.hasNext()) source.next(); } public boolean hasNext() { return source.hasNext(); } public X next(){ X n = source.next(); // skip the next one if (source.hasNext()) source.next(); return n; } }
source share