Hello All at the Ranch:
I am puzzeling with the idea of Filtered Iterator.
Actually I have heard that it has become a common interview question.
Say I had a class that looked like this:
public class BigBall {
private
String color;
private int size;
public BigBall(String c_in, int s_in) {
this.color = c_in;
this.size = s_in;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
}
And I want to create a filter class like this:
public class TestColor implements IObjectTest {
//IObjectTest interface is down below
String[] color; //color to look for
TestColor(String[] c_in){
color = new String[ c_in.length];
System.arraycopy( c_in, 0, color, 0, c_in.length );
}
public boolean
test(BigBall b_in) {
for (String s : color ) {
if ( s.equalsIgnoreCase(b_in.getColor() ) )
return true;
}
return false;
}
@Override
public boolean test(Object o) {
// TODO Auto-generated method stub
return false;
}
}
What I want to do is have a list of BigBalls and have an iterator that only returns the red ones.
or the ones that match the colors in TestColor.color.
so I need override IObjectTest.test(Object o) If I do the following:
@Override
public boolean test(Object o) {
// TODO Auto-generated method stub
for (String s : color ) {
if ( s.equalsIgnoreCase(o.getColor() ) )
return true;
}
return false;
}
I get getColor() is undefined for type Object
Which makes sense.
I guess what I am missing is how do I go from the
IObjectTest interface to class that tests a specific object, like BigBall.
Hope this make sense.
Best Regards
KD
** ** ** ** ** ** **
** borrowed code
import java.util.Iterator;
public class FilterIterator implements Iterator<Object> {
private final Iterator<Object> wrapped;
private final IObjectTest predicate;
private Object next;
FilterIterator(Iterator<Object> wrapped, IObjectTest predicate) {
this.wrapped = wrapped;
this.predicate = predicate;
}
@Override
public boolean hasNext() {
while (next == null && wrapped.hasNext()) {
next = wrapped.next();
if (predicate.test(next))
return true;
next = null;
}
return next != null;
}
@Override
public Object next() {
if (next == null)
hasNext();
try {
return next;
} finally {
next = null;
hasNext();
}
}
@Override
public void remove() {
wrapped.remove();
}
}
public interface IObjectTest {
boolean test(Object o);
}
source for above code is from
https://github.com/rickyclarkson/interviewquestions/tree/master/src/main/java/iterators