I’d like to implement an iterator that retrieves objects from disk/network.
Iterator itr = getRemoteIterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
However the problem is that hasNext() and next() methods of the Iterator object does not allow to throw IOException. Is there any other standard interface work around this issue?
Desired code is:
public interface RemoteIterator<E> {
boolean hasNext() throws IOException;
E next() throws IOException;
void remove();
}
It isn’t exactly what you want, but consider:
This is happening over a network, so it may be slow. You should be probably be using a
Future(or similar).So, instead of having your
RemoteIterator<E>wherenext()returns a E, useRemoteIterator<Future<E>>, where it returns aFuture<E>.In the
Future.get()method, you can wrap anyIOExceptionin anExecutionException.Not perfect, but
Future.get()implies that things may be slow, plus it does throw a checked exception which will tip off other programmers what is happening, and the natural response is to callgetCause(). So this avoids most of the “WTF” aspects.