You are viewing a plain text version of this content. The canonical link for it is here.
Posted to user@commons.apache.org by wa...@earthlink.net on 2004/06/14 17:05:29 UTC

Apache Commons BeanUtils ResultSetIterator bug?

While browsing through the source code for ResultSetIterator in version 1.6.1 I found the following code snippet:

    public boolean hasNext() {
        try {
            advance();
            return (!eof);
        } catch (SQLException e) {
            throw new RuntimeException("hasNext():  SQLException:  " + e);
        }
    }

    public Object next() {

        try {
            advance();
            if (eof) {
                throw new NoSuchElementException();
            }
            current = false;
            return (this);
        } catch (SQLException e) {
            throw new RuntimeException("next():  SQLException:  " + e);
        }
    }

If someone were to use it in the normal format in which the hasNext() and next() methods are used, the person would skip over one row in the resultset for every iteration of the iterator since both methods call unconditionally the advance() method, which advances the resultset by one.

I propose that a flag variable be introduced into the iterator class so that the next() method would conditionally advance the resultset by one only if no previous hasNext() method has been called. The following is my proposed code change:

    private boolean hasNextCalled = false;	
    /**
     * <p>Return <code>true</code> if the iteration has more elements.</p>
     */
    public boolean hasNext() {
        try {
            advance();
            hasNextCalled = true;
            return (!eof);
        } catch (SQLException e) {
            throw new RuntimeException("hasNext():  SQLException:  " + e);
        }
    }
    /**
     * <p>Return the next element in the iteration.</p>
     */
    public Object next() {

        try {
        	if(!hasNextCalled)
            {
            	advance();
            }
            else
            {
            	hasNextCalled = false; 
            }
            if (eof) {
                throw new NoSuchElementException();
            }
            current = false;
            return (this);
        } catch (SQLException e) {
            throw new RuntimeException("next():  SQLException:  " + e);
        }
    }


What do you guys think?

---------------------------------------------------------------------
To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org
For additional commands, e-mail: commons-user-help@jakarta.apache.org