简体   繁体   English

如何计算arraylist中特定类的实例数?

[英]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. 我想知道在数组列表中提取Class1实例数的最有效方法。

For the above example, I want the answer 3. 对于上面的例子,我想要答案3。

I am using Java version "1.7.0_79". 我使用的是Java版“1.7.0_79”。

You could iterate through the ArrayList and check using the instanceof operator. 您可以遍历ArrayList并使用instanceof运算符进行检查。

for (Object e : lst)
{
  if (e instanceof Car)
  {
    carCount++;
  }
}

You can need to check the class at any given position in the array by using the keyword instanceof 您可以使用关键字instanceof在数组中的任何给定位置检查类

Example: 例:

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");
}

if the arraylist is like below, 如果arraylist如下所示,

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 如果您总是添加Class1的新实例,那么下面将是解决方案

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

override equals method in Class1 like below, 覆盖等于Class1中的方法,如下所示,

 @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()));

Well, You can easily filter them by 好吧,你可以轻松过滤它们

result = Iterables.filter(collection, YourClass.java);

then you can apply .size() on the result. 然后你可以在结果上应用.size()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM