SHE SHE - 1 month ago 7
Java Question

Find last object from a list of objects, throw exception if not found

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:


  1. Do we need the
    throws NoSuchElementException
    in the method header?

  2. Do we need
    try catch
    block in the last line inside the method? If so, how?

  3. Is this code works?


Answer

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);
}
Comments