关闭java.util.Iterator [英] Closing a java.util.Iterator

查看:126
本文介绍了关闭java.util.Iterator的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用应该使用 close()方法在最后发布的资源实现了自定义 java.util.Iterator 。该资源可以是 java.sql.ResultSet java.io.InputStream 等......

I've implemented a custom java.util.Iterator using a resource that should be released at the end using a close() method. That resource could be a java.sql.ResultSet, a java.io.InputStream etc...

public interface CloseableIterator<T> extends Iterator<T>
  {
  public void close();
  }

使用此迭代器的一些外部库可能不知道必须关闭它。例如:

Some external libraries using this iterator might not know that it must be closed. e.g:

public boolean isEmpty(Iterable<T> myiterable)
 {
 return myiterable.iterator().hasNext();
 }

在这种情况下,有没有办法关闭这个迭代器?

In that case, is there a way to close this iterator?

更新:非常感谢您当前的答案。我会给每个人一个(+1)。当 hasNext()返回false时,我已经关闭了Iterator。我的问题是当循环迭代在最后一次迭代之前中断时,如我的例子所示。

Update: many thanks for the current answers . I'll give a (+1) to everybody. I do already close the Iterator when hasNext() returns false. My problem is when the loop iterating breaks before the last iteration as it is shown in my example.

推荐答案

问题是条件在最后。我们经常迭代完整的集合或数据集,所以我们现在末尾,没有数据可供阅读。

The problem is the condition at the end. Often we iterate over a full collection or data set, so we're at the end at the moment, there's no data left to read.

但是如果我们在到达数据结束之前设置了循环中断,则迭代器将不会结束并且不会被关闭。

But if we set a break out of the loop before we reached the End Of Data, the iterator wouldn't come to an end and wouldn't be closed.

一种出路可能是在构造期间将数据源的内容缓存在迭代器中并关闭资源。所以迭代器不能在打开的资源上工作,而是在缓存数据上工作。

A way out could be to cache the content of the data source in the iterator during construction and close the resource. So the iterator would not work on the opened resource but on cached data.

这篇关于关闭java.util.Iterator的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆