If a class implements the Iterable interface, e.g.
class Query implements Iterable<Query.Entry> {
class Entry {
// ...
}
@Override
public Iterator<Entry> iterator() {
return new EntryIterator();
}
}
then using an enhanced for is possible,
Query q;
// ...
for( Query.Entry e : q ) {
// ...
}
but now needs to support other ways to perform iteration, e.g.
class Query implements Iterable<Query.Entry> {
class Entry {
// ...
}
@Override
public Iterator<Entry> iterator() {
return new EntryIterator();
}
// new methods for reverse iteration
public Iterator<Entry> reverseIterator() {
return new ReverseEntryIterator();
}
public Iterable<Entry> reverseIterable() {
return new Iterable<Entry>() {
@Override
public Iterator<Entry> iterator() {
return new ReverseEntryIterator();
}
};
}
}
would there be a "standard" way of doing this? The above code adds reverseIterable and reverseIterator, but looks somewhat messy. Maybe its better style to do without a reverseIterable method?
reverseIteratormethod. It is pretty rare for your own code to need to deal with anIteratordirectly, and if you really want one then you can callreverseIterable().iterator(). Also note that you can neaten up thereverseIteratormethod by just returningReverseEntryIterator::newin Java 8+.Listprovides both iterator() and listIterator(), so this looks like a fairly reasonable approach.