Use of instanceof

Asked

Viewed 679 times

3

Create an abstract class Conta, and two other concrete classes ContaF and ContaJ inherited from the main class. Create another class with a method that receives a list of contaF and ContaJ and ArrayList<Conta> and calculate how many elements it has in ContaF and ContaJ

I’m about to finish:

public class InstanciaDe 
{

public static void main( String[] args )
{

    ContaF Rafael = new ContaF();

    ContaJ Roberto = new ContaJ();      

    ContaJ Carlos = new ContaJ();  

    ArrayList<Conta> lista = new ArrayList<Conta>();        

    lista.add(Rafael);
    lista.add(Roberto);
    lista.add(Carlos);

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


        if (lista.get(i) instanceof ContaF) {

        }       

        if (lista.get(i) instanceof ContaJ) {

        }
    }  
}
}

How can I save the amount by instanceof each and then display?

  • int nContaF = 0; if(lista.get(i) instanceof ContaF) nContaf++;

  • Thank you, I was thinking of something similar.

2 answers

4


Just create an accountant:

import java.util.*;

class InstanciaDe {
    public static void main( String[] args ) {
        int contaF = 0;
        int contaJ = 0;
        ContaF Rafael = new ContaF();
        ContaJ Roberto = new ContaJ();
        ContaJ Carlos = new ContaJ();
        ArrayList<Conta> lista = new ArrayList<Conta>();        
        lista.add(Rafael);
        lista.add(Roberto);
        lista.add(Carlos);
        for(int i = 0 ; i < lista.size() ; i++) {
            if (lista.get(i) instanceof ContaF) {
                contaF++;
            }       
            if (lista.get(i) instanceof ContaJ) {
                contaJ++;
            }
        }
        System.out.println(contaF);
        System.out.println(contaJ);
    }
}
class Conta {}
class ContaF extends Conta {}
class ContaJ extends Conta {}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • It was very helpful, thank you.

1

import java.util.*;

class Conta {}
class ContaF extends Conta {}
class ContaJ extends Conta {}

class InstanciaDe {

    public static void main(String[] args) {
        ContaF Rafael = new ContaF();

        ContaJ Roberto = new ContaJ();      

        ContaJ Carlos = new ContaJ();  

        ArrayList<Conta> lista = new ArrayList<Conta>();        

        lista.add(Rafael);
        lista.add(Roberto);
        lista.add(Carlos);

        System.out.println(getInstanceCount(contas, ContaF.class));
        System.out.println(getInstanceCount(contas, ContaJ.class));
    }

    public static int getInstanceCount(List<Conta> contas, Class<? extends Conta> class1) {
        int count = 0;

        for (Conta conta : contas) {
            if (conta.getClass().equals(class1)) {
                count++;
            }
        }

        return count;
    }
}

Browser other questions tagged

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