Check the arrayList object at runtime

Asked

Viewed 110 times

2

I have an arraylist with three positions. I added to the array, objects like Manager, Seller and Technician, respectively. Using the getClass, would like to know how do I know which object is in each vector position.

I did it this way, but it didn’t make any mistakes and it didn’t call my methods.

public static void mostrarSalarioFuncionario() {

        ArrayList<Funcionario> listaFunc = new ArrayList<Funcionario>();
        listaFunc.add(ge);
        listaFunc.add(te);
        listaFunc.add(ve);
        System.out.println("CALCULO SALARIO DO FUNCIONARIO");
        for (int i = 0; i < listaFunc.size(); i++) {


            if (listaFunc.get(i).getClass().equals(ge) {
                System.out.println("Classe...:Gerente");
                System.out.println("Salário..:"+ge.calcularSalario());;
            }

            else if(listaFunc.get(i).getClass().equals(ve)) {
                System.out.println("Classe...:Vendedor");
                System.out.println("Salário..:"+ve.calcularSalario());;
            }

            else if (listaFunc.get(i).getClass().equals(te)) {
                System.out.println("Classe...:Técnico");
                System.out.println("Salário..:"+te.calcularSalario());
            }
}
  • Use instance of instead of getClass. I’d even show you an example, but this bit of code doesn’t make sense with the doubt of the question.

  • reformulated the question could exemplify with instance of?

  • What is you and see?

  • an object of the type Seller and the type Tecnico

1 answer

2


Utilize instanceof to check the object subtype:

for (int i = 0; i < listaFunc.size(); i++) {

    System.out.println("Classe:"+listaFunc.get(i).getClass().getName().substring(32));
    if (listaFunc.get(i) instanceof Gerente) {
        System.out.println("Classe...:Gerente");
        System.out.println("Salário..:"+ge.calcularSalario());;
    }

    else if(listaFunc.get(i) instanceof Vendedor) {
        System.out.println("Classe...:Vendedor");
        System.out.println("Salário..:"+ve.calcularSalario());;
    }

    else if (listaFunc.get(i) instanceof Tecnico) {
        System.out.println("Classe...:Técnico");
        System.out.println("Salário..:"+te.calcularSalario());
    }
}
  • really so it was much easier, my doubt was whether with instance of would need the . get(i). Thanks again diegofm

  • @Diogolopes instanceof checks if an object on the left is of the class type on the right, then it would need to get(i), since this method returns the instantiated object that is in the list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.