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:
throws NoSuchElementException
in the method header?try catch
block in the last line inside the method? If so, how?You don't need to declare NoSuchElementException
because it's not a checked exception (it's a runtime exception, like NPE).
You don't need the try catch block when calling it, because unchecked exceptions don't need to be caught.
The code works by returning as soon as it finds a Bar
, but if the loop ends without finding one, the exception is thrown.
Alternative implementation:
Bar findLast(List stuff) {
return stuff.stream().filter(o -> o instanceof Bar).findFirst().orElseThrow(NoSuchElementException::new);
}