Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for each, but multiple iterator types?

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?

like image 604
Engineer Avatar asked Sep 15 '10 15:09

Engineer


1 Answers

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

like image 145
GHad Avatar answered Oct 31 '22 12:10

GHad