Using instanceof

3

Create an abstract class Conta , and two other concrete classes ContaF and ContaJ that inherit 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 almost done:

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 quantity by instanceof of each and then display?

    
asked by anonymous 15.03.2016 / 17:52

2 answers

4

Just create a counter:

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 {}

See running on ideone .

    
15.03.2016 / 18:08
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;
    }
}
    
15.03.2016 / 19:01