Java Iterator backed by a ResultSet

后端 未结 17 740
清歌不尽
清歌不尽 2020-12-13 06:51

I\'ve got a class that implements Iterator with a ResultSet as a data member. Essentially the class looks like this:

public class A implements Iterator{
            


        
17条回答
  •  星月不相逢
    2020-12-13 07:23

    You can get out of this pickle by performing a look-ahead in the hasNext() and remembering that you did a lookup to prevent consuming too many records, something like:

    public class A implements Iterator{
        private ResultSet entities;
        private boolean didNext = false;
        private boolean hasNext = false;
        ...
        public Object next(){
            if (!didNext) {
                entities.next();
            }
            didNext = false;
            return new Entity(entities.getString...etc....)
        }
    
        public boolean hasNext(){
            if (!didNext) {
                hasNext = entities.next();
                didNext = true;
            }
            return hasNext;
        }
        ...
    }
    

提交回复
热议问题