Requirements: find last Bar object from a list of different objects, throw NoSuchElementException if not find
Bar findLast(List stuff) throws NoSuchElementException { }
My solution:
Bar findLast(List stuff) throws NoSuchElementException {
Bar bar = new Bar();
for(int i=stuff.size()-1;i>=0;i--){
if(stuff.get(i).getClass().isInstance(bar)){
return (Bar) stuff.get(i);
}
}
throw new NoSuchElementException();
}
Questions:
- Do we need the
throws NoSuchElementException
in the method header? - Do we need
try catch
block in the last line inside the method? If so, how? - Is this code works?