I have a class Polygon on which I wish to implement two iterators: one to run through all elements (vertices and edges in alternating order) just ONCE, and another to run through them ad infinitum (cyclically).
From a for-each usage standpoint, my guess is that I am only going to be able to have one of the above be the default iterator that can be used with for-each, via implementation of Iterable.iterator(). Is this correct? Or is there a way I could use for-each with both?
Just add two methods returning two different Iterators, one for each case:
public Iterable<String> eachOnce() {
    List<String> allResults = new ArrayList<String>();
    // fill list
    return allResults;
}
public Iterable<String> eachCyclic() {
    return new Iterable<String>() {
        public Iterator<String> iterator() {
            return new Iterator<String>() {
                public boolean hasNext() {
                    return true;
                }
                public String next() {
                    // TODO implement
                    return null;
                }
                public void remove() {
                    // do nothing
                }
            };
        }
    };
}
This is just an example with a List of Strings, just adapt.
Instead of
for (Polygon p : polygons) { }
just use
for (Polygon p : polygons.eachOnce()) { }
or the cyclic edition
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With