Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare my method to receive any kind of list as argument?

Tags:

java

arraylist

public static int menu(String texto, ArrayList<String> opciones) {
    for (int i = 0; i < opciones.size(); i++) {
        System.out.println((i + 1) + ") " + opciones.get(i));
    }

    return solicitarNumero(texto + " [1-"
            + opciones.size() + "]", true, 1, opciones.size());
}

I have this method that receives a text (texto) prompting the user to input an option number and an ArrayList with the options. e.g. {Create entry, remove entry, quit}

solicitarNumero handles the request of the option number and verifies it.

Right now when I'm calling this method using variables of different classes (Franquicia, Gerente, Sistema) I have to go over each ArrayList and create a new one containing that class' toString.

Like so

for (Franquicia franquicia : listaFranquicia) {
    listaDatosFranquicia.add(franquicia.toString());
}

Then I use the method with the new ArrayList.

menu("Ingrese el numero de franquicia "
            + "que desea asignar a este control",
            listaDatosFranquicia) - 1));

Is there a way I could simply do

menu("Ingrese el numero de franquicia "
            + "que desea asignar a este control",
            listaFranquicia) - 1));

Without having to create a new ArrayList?

like image 572
user2020618 Avatar asked Dec 03 '25 09:12

user2020618


1 Answers

Yes. Change the method to

public static int menu(String texto, List<?> opciones) {
    for (int i = 0; i < opciones.size(); i++) {
        System.out.println((i + 1) + ") " + opciones.get(i));
    }

    return solicitarNumero(texto + " [1-"
            + opciones.size() + "]", true, 1, opciones.size());
}

which is basically equivalent to:

public static int menu(String texto, List<?> opciones) {
    for (int i = 0; i < opciones.size(); i++) {
        System.out.println((i + 1) + ") " + opciones.get(i).toString());
    }

    return solicitarNumero(texto + " [1-"
            + opciones.size() + "]", true, 1, opciones.size());
}

unless one of your options is null (in which case the second one will cause a NullPointerException, whereas the first one will print "null").

List<?> means: a list of some unknown type. But since all types extend java.lang.Object, and all you care about is the toString() representation of the objects, you don't really need to know the actual generic type of the list.

like image 127
JB Nizet Avatar answered Dec 07 '25 15:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!