我想实现一个从磁盘/网络检索对象的迭代器。
Iterator itr = getRemoteIterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
但是问题在于 Iterator 的 hasNext()
和 next()
方法对象不允许抛出 IOException
。是否有任何其他标准接口(interface)可以解决此问题?
所需的代码是:
public interface RemoteIterator<E> {
boolean hasNext() throws IOException;
E next() throws IOException;
void remove();
}
最佳答案
这不是您想要的,但请考虑:
这是通过网络进行的,因此速度可能很慢。您可能应该使用 Future
(或类似的)。
所以,不用你的 RemoteIterator<E>
其中 next()
返回一个 E,使用
RemoteIterator<Future<E>>
,它返回一个 Future<E>
.
在Future.get()
方法,你可以包装任何 IOException
在ExecutionException
.
不完美,但 Future.get()
暗示事情可能会很慢,而且它确实会抛出一个已检查的异常,这会提示其他程序员正在发生的事情,自然的 react 是调用 getCause()
.因此,这避免了大多数“WTF”方面。
关于java - 如何创建抛出 IOException 的 Java 迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12801665/