Skip to content

Instantly share code, notes, and snippets.

@coopernurse
Created February 10, 2016 23:56
Show Gist options
  • Save coopernurse/7b88671292860b49a835 to your computer and use it in GitHub Desktop.
Save coopernurse/7b88671292860b49a835 to your computer and use it in GitHub Desktop.
import java.util.Iterator;
import java.util.NoSuchElementException;
public abstract class BaseIterator<T> implements Iterator<T> {
private T nextItem;
@Override
public boolean hasNext() {
return fetchNext() != null;
}
@Override
public T next() {
T item = fetchNext();
if (item == null) {
throw new NoSuchElementException("iterator exhausted");
}
else {
nextItem = null;
return item;
}
}
private T fetchNext() {
if (nextItem == null) {
nextItem = loadNext();
}
return nextItem;
}
// try to load next. return null if no item found
public abstract T loadNext();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment