Skip to content

Instantly share code, notes, and snippets.

@arthurnn
Created July 28, 2011 21:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arthurnn/1112592 to your computer and use it in GitHub Desktop.
Save arthurnn/1112592 to your computer and use it in GitHub Desktop.
FilterIteratorImpl
/* only output for valid = true */
interface FilterIterator {
public boolean hasNext();
public Object next();
}
interface Filter {
boolean valid(Object o);
}
/* 2 params for constructor, source Iterator, and filter object */
public FilterIteratorImpl implements FilterIterator{
Iterator i;
Filter f;
Object _nextObj = null;
boolean open = false;
public FilterIteratorImpl(Iterator source,Filter f){
this.f = f;
this.i = source;
//get the root at the first time
open = true;
_nextObj = this.next()
open = false;
}
public boolean hasNext(){
return null!=_nextObj;
}
public Object next(){
// return the root if it is the first time
if(!open){
return _nextObj;
open = true;
}
//reset the next obj, so we make sure that if we dont have a next one, will be null
_nextObj = null;
// keep getting, till we get a valid one
while(i.hasNext()){
_nextObj = i.next();
if(f.valid(_nextObj)) break;
else _nextObj = null;
}
return _nextObj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment