How to return a data type for "Reference"?

2

At the moment of executing it does not show me any Bajo . I would like to know how I can return the element.

I attach code.

public Bajo buscar(String nombre, String referencia){
    Bajo respuesta= null;
    for(int i=0;i< bajos.size();i++){
        Bajo actual=(Bajo) bajos.get(i);
        if(actual.darNombre().equals(nombre) 
                && actual.darReferencia().equals(referencia)){
            respuesta= actual;
        }
    }
    return respuesta;
}
    
asked by Diego 14.06.2016 в 21:27
source

1 answer

1

The code you show should work without problems. Maybe what you want is to show the content of the element. If you are in a console application, you should use System.out.println :

Bajo bajo = buscar("nombre", "referencia");
if (bajo != null) {
    System.out.println(String.format("Este es un bajo %s con referencia %s", bajo.darNombre(), bajo.darReferencia()));
}

If you want to print directly using the returned variable, you should write about the toString method in the class Bajo :

public class Bajo {
    /* definición actual */
    @Override
    public String toString() {
        return String.format("Bajo. Nombre: %s. Referencia: %s",
                darNombre(), darReferencia());
    }
}

And the previous code would be written:

Bajo bajo = buscar("nombre", "referencia");
if (bajo != null) {
    System.out.println(bajo);
}

While it is true that the code works, you can take advantage of the benefits of the List interface and convert that for into a for improved that resembles for-each of other languages:

public Bajo buscar(String nombre, String referencia){
    Bajo respuesta= null;
    //for(int i=0;i< bajos.size();i++){
    //    Bajo actual=(Bajo) bajos.get(i);
    //la línea de abajo reemplaza a las líneas anteriores
    //y es más eficiente puesto que utiliza un Iterator
    //el método get(i) puede tomar más tiempo en algunas implementaciones
    for (Bajo actual : bajos) {
        if (actual.darNombre().equals(nombre)
                && actual.darReferencia().equals(referencia)) {
            respuesta = actual;
            break; //importante! detiene el ciclo for
        }
    }
    return respuesta;
}
    
answered by 14.06.2016 / 21:30
source