Java Reference
In-Depth Information
21.13. Writing Iterator Implementations
Iterators are generally useful, and you may want to write your own, even
if you are not implementing a collection type. The following code demon-
strates the basics of writing your own Iterator implementation, in this
case for an iterator that will filter out strings longer than a given length:
public class ShortStrings implements Iterator<String> {
private Iterator<String> strings; // source for strings
private String nextShort; // null if next not known
private final int maxLen; // only return strings <=
public ShortStrings(Iterator<String> strings,
int maxLen) {
this.strings = strings;
this.maxLen = maxLen;
nextShort = null;
}
public boolean hasNext() {
if (nextShort != null) // found it already
return true;
while (strings.hasNext()) {
nextShort = strings.next();
if (nextShort.length() <= maxLen)
return true;
}
nextShort = null; // didn't find one
return false;
}
public String next() {
if (nextShort == null && !hasNext())
throw new NoSuchElementException();
String n = nextShort; // remember nextShort
nextShort = null; // consume nextShort
return n; // return nextShort
}
 
Search WWH ::




Custom Search