Created
July 28, 2011 21:20
-
-
Save arthurnn/1112592 to your computer and use it in GitHub Desktop.
FilterIteratorImpl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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