How to implement this FilteringIterator?

advertisements
  1. IObjectTest is a interface with a single boolean test(Object o) method

  2. FilteringIterator is an implementation of Iterator which is initialized with another Iterator and an IObjectTest instance: new FilteringIterator(myIterator, myTest). Your FilteringIterator will then allow iteration over 'myIterator', but skipping any objects which don't pass the 'myTest' test.

Since the "hasNext" operation actually involve repeatly moving the underlying iterator untill reach the next matching item. The question is how can it move it iterator back since hasNext is not supposed to move the underlying iterator.


You would need to make your iterator stateful. Cache the last value you retrieved from hasNext and use that from the next method, if it exists.

private boolean hasCached;
private T cached;

public boolean hasNext() {
   if ( hasCached ) return true;
   //iterate until you find one and set hasCached and cached
}

public T next() {
   if ( hasCached ) {
      hasCached = false;
      return cached;
   }
   //iterate until next matches
}