Question

So there's Iterable and Iterator and List. What do you use if you are trying to provide an interface to other Java code, in order to encapsulate functionality provided by a remote service that returns results in "pages"?

As an example, consider a database or a webpage (e.g. flickr API). After the first retrieval of results, you know the total # of results and the first N results, but you don't know the remaining results until you retrieve the rest.

Was it helpful?

Solution 3

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();
}

OTHER TIPS

In your case, given that each element is expensive to retrieve, it probably makes sense to take aggregate results and not iterate directly for each element at remove invocation level.

You could provide one method which returns a List like this:

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

where offset would be the index of the first element you want to start from and maxresults is the maximum number of elements you want to have in the list. You can then iterate on the list to display in your page.

The Java Persistence API also follows the same pattern, the Query interface provides 3 methods that do the above:

setFirstResult()
setMaxResults()
List getResultList()

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

I would stay compliant with Iterator interface, and wouldn't introduce new methods (as suggested above). Instead I would use lazy loading in hasElements(), nextElement(), and your class getters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top