I have a list of objects and want to iterate in forwards and backwards, until an element is found that is "valid".
MyClass {
private boolean valid;
public boolean isValid() { return valid; }
}
List<MyClass> classes; //assume sorted list
Now I want to start at position idx
, and iterate both forwards and backwards to find the closest element that is valid. So far I already got the forward algorithm working. But I feel that the code could be optimized:
//supposed to start at position X
int idx = 10;
//find the closest element that is valid
for (ListIterator<MyClass> itr = classes.listIterator(idx); itr.hasNext();) {
if (itr.hasNext()) {
MyClass my = itr.next();
while (!my.isValid()) {
if (itr.hasNext()) {
my = itr.next();
} else {
break;
}
}
}
Sysout("the closest valid element is: " + my);
}
Could the iterator algorithm be written better?