Queryable Iterator

One ugly attempt to code a QueryableIterator and its utilization. Moved from IteratorSemanticsAreWrong

After coding a QueryableIterator that wrapped Iterator and added a repeatable read, and coding a ProposedIterator, I have changed my mind in favor of ProposedIterator as a general solution. Adding code to utilize a repeatable read without the isValid() semantics of ProposedIterator resulted in CodeBloat.

[original example deleted due to mangling edits]

--KentDorsey

I can't figure out what the historicalObject is supposed to do. It's private, and only appears as an lvalue. Assuming its an artifact that hasn't been factored out yet, here's a slightly better implementation. The main difference (beside lacking the historicalObject) is tracking whether a current object is available. It makes sense that an element can't be accessed once it has been deleted, or before the first call to next(). Also, nulling currentObject once it has been removed from the collection allows the garbage collector to do its thing.

   public class QueryableIterator implements Iterator {

Iterator iter; Object currentObject; boolean currentAvail;

public QueryableIterator(Iterator i) { iter = i; }

public boolean hasNext() { return iter.hasNext(); }

public boolean hasCurrent() { return currentAvail; }

public Object next() { currentObject = iter.next(); currentAvail = true; return currentObject; }

public void remove() { iter.remove(); currentAvail = false; currentObject = null; }

public Object current() { if (currentAvail) { return currentObject; } else { throw new IllegalStateException(); } }

}

--CraigPutnam


EditText of this page (last edited June 3, 2004) or FindPage with title or text search