Java – how to calculate the number of instances of a specific class in ArrayList?
•
Java
I have an array list that looks like:
[new Class1(),new Class2(),new Class1(),new Class1()]
I want to know the most effective way to extract the number of Class1 instances from the array list
For the above example, I want answer 3
I use the Java version of "1.7.0_79"
Solution
If ArrayList is as follows,
newClass1 = new Class1(); [newClass1,newClass1,newClass1]
Then you can check the following frequencies,
Collections.frequency(arrayList,newClass1);
If you always add new instances of Class1, here is the solution
[new Class1(),new Class1()]
Override is equal to the method in Class1, as shown 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()));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码