DavidVV DavidVV - 3 months ago 11
Java Question

Java: Implementing search function. Return fails if not found

I am trying to implement a search function. The function returns an object of type Prestamo if it finds a matching element. The function shouldn't return anything if nothing is found, but I get (of course) an error complaining about a missing return statement. How is this kind of problem solved? I guess Try-catch could be my friend for this, but I am struggling to understand that syntax.

This is my code:

public Prestamo buscarPrestamoPorUUID(UUID idPrestamo, ArrayList<Prestamo> listaBuscar) {
Iterator<Prestamo> it = listaBuscar.iterator();
Prestamo esteElemento;
while (it.hasNext()) {
esteElemento = it.next();
if (esteElemento.getActivo() && esteElemento.getIdPrestamo().equals(idPrestamo)) {
return esteElemento;
}
}
}

Answer

In Java, the control over a method must end in one of two ways:

  1. A return statement, which returns an object of the type declared in the method signature OR null
  2. A thrown exception (if the Exception does not extend RuntimeException, it must be declared in the method signature).

To resolve your compilation error, you need to do one of the two. If you want to do the former, it'd probably look something like this:

public Prestamo buscarPrestamoPorUUID(UUID idPrestamo, ArrayList<Prestamo> listaBuscar) {
    Iterator<Prestamo> it = listaBuscar.iterator();
    Prestamo esteElemento;
    while (it.hasNext()) {
        esteElemento = it.next();
        if (esteElemento.getActivo() && esteElemento.getIdPrestamo().equals(idPrestamo)) {
            return esteElemento;
        }
    }
    return null;
}

Just be sure that the logic that invokes this method is prepared to handle null.

If you want to do the second, you'd do something like this:

public Prestamo buscarPrestamoPorUUID(UUID idPrestamo, ArrayList<Prestamo> listaBuscar) {
    Iterator<Prestamo> it = listaBuscar.iterator();
    Prestamo esteElemento;
    while (it.hasNext()) {
        esteElemento = it.next();
        if (esteElemento.getActivo() && esteElemento.getIdPrestamo().equals(idPrestamo)) {
            return esteElemento;
        }
    }

    throw new RuntimeException("Didn't find an entity with the provided UUID!");
}

I personally prefer the former to the latter. It's a perfectly-valid use of null, and it makes the method easier to use than having to worry about uncaught exceptions. Regardless, note how that either implementation reaches a return or throw statement eventually. That's what your compiler checks for.

(P.S.: You can replace your while-loop with a for-each loop for code clarity.)

Comments