8

所以有IterableIteratorList。如果您尝试为其他 Java 代码提供接口,以封装远程服务提供的功能,该功能在“页面”中返回结果,您会使用什么?

例如,考虑一个数据库或网页(例如flickr API)。在第一次检索结果后,您知道结果的总数和前 N 个结果,但在检索其余结果之前,您不知道剩余的结果。

4

3 回答 3

5

在您的情况下,鉴于每个元素的检索成本很高,因此获取聚合结果而不是在 remove 调用级别直接迭代每个元素可能是有意义的。

您可以提供一种返回 List 的方法,如下所示:

List<YourClass>  getResults(int offset, int maxResults)

其中 offset 是您要开始的第一个元素的索引,而 maxresults 是您希望在列表中拥有的最大元素数。然后,您可以迭代列表以显示在您的页面中。

Java Persistence API 也遵循相同的模式,Query 接口提供了 3 个方法来执行上述操作:

setFirstResult()
setMaxResults()
List getResultList()

http://download.oracle.com/javaee/5/api/javax/persistence/Query.html

于 2010-12-28T00:16:18.753 回答
3

我会保持与接口兼容Iterator,并且不会引入新方法(如上所述)。相反,我会在,和你的类吸气剂中使用延迟加载。hasElements()nextElement()

于 2011-01-05T08:19:08.737 回答
1

In my application I decided to implement Iterator<ListPage>, where the iterator's implementation of next() is to download the next page of results, and ListPage has methods that return the real List and the metadata like total # of results, # per page, page #, and total # of pages:

public interface ListPage<T> {
    public List<T> getList();
    public int getTotal();
    public int getPage();
    public int getPages();
    public int getPerPage();
}
于 2011-01-05T13:35:52.907 回答