Search code examples
javajava-7

How to count number of instances of specific class in arraylist?


I have an array list that looks like:

[new Class1(), new Class2(), new Class1(), new Class1()]

I want to know the most efficient way to extract the number of instances of Class1 in the array list.

For the above example, I want the answer 3.

I am using Java version "1.7.0_79".


Solution

  • if the arraylist is like below,

    newClass1 = new Class1();
    
    [newClass1, new Class2(), newClass1, newClass1]
    

    then you can check the frequency like below,

    Collections.frequency(arrayList, newClass1);
    

    If you are always adding new instance of Class1 then below will be the solution

    [new Class1(), new Class2(), new Class1(), new Class1()]
    

    override equals method in Class1 like below,

     @Override
    public boolean equals(Object o){
    
        if(!(o instanceof Class1 )){
            return false;
        }else{
    
                return true;
        }
    }
    

    then in your test class,

    System.out.println(Collections.frequency(array, new Class1()));