SHE SHE - 1 year ago 96
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--){
return (Bar) stuff.get(i);
throw new NoSuchElementException();


  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 Source

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 -> o instanceof Bar).findFirst().orElseThrow(NoSuchElementException::new);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download