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".
You could iterate through the ArrayList and check using the instanceof
operator.
for (Object e : lst)
{
if (e instanceof Car)
{
carCount++;
}
}
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()));
You can need to check the class at any given position in the array by using the keyword instanceof
public static void main(String[] args) {
Number[] myN = new Number[5];
//populate... ignore this if want
for (int i = 0; i < myN.length; i++) {
if (i%2==0) {
myN[i]= new Integer(i);
}else{
myN[i]= new Double(i);
}
}
int classACounter=0;
int classBCounter=0;
//check
for (int i = 0; i < myN.length; i++) {
if (myN[i] instanceof Integer){
System.out.println(" is an int");
classACounter++;
}
if (myN[i] instanceof Double){
System.out.println(" is a double");
classBCounter++;
}
}
System.out.println("There are "+classACounter+" elements of the class A");
System.out.println("There are "+classBCounter+" elements of the class B");
}
Well, You can easily filter them by
result = Iterables.filter(collection, YourClass.java);
then you can apply .size()
on the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With