Java Iterator backed by a ResultSet

后端 未结 17 743
清歌不尽
清歌不尽 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:18

    You could try the following:

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

    This code caches the next entity, and hasNext() returns true, if the cached entity is valid, otherwise it returns false.

提交回复
热议问题