简体   繁体   English

如何遍历不同 class 对象的 ArrayList 以搜索特定的 class?

[英]How can I iterate through an ArrayList of the different class objects to search for a specific class?

How can I iterate through an ArrayList of the different class objects to search for a specific class?如何遍历不同 class 对象的 ArrayList 以搜索特定的 class?

productionDate is an interface that is implemented in base classes. productionDate 是在基类中实现的接口。

Here is the code but it doesn't print anything:)这是代码,但它不打印任何东西:)

ArrayList<ProductionDate> storage;

public void search(Class c, int itemCount){
   if(storage.getClass() == c){
       for(ProductionDate d : storage){
           if(d instanceof ProductionDate &&
                   ((ProductionDate)d).getItemCount() >= itemCount){
                     System.out.println(d);
           }
       }
   }
}

First, Remove the first if statement.首先,删除第一个 if 语句。

Secondly, You should use the class that implements ProductionDate interface in order to check whether the object belongs to that specific class. I think that class is Class c here.其次,你应该使用实现ProductionDate接口的class来检查object是否属于那个特定的class。我认为class在这里是Class c

So:所以:

ArrayList<ProductionDate> storage;

public void search(Class c, int itemCount){
    for(ProductionDate d : storage){
           if(d instanceof c &&
                   ((c)d).getItemCount() >= itemCount){
                     System.out.println(d);
           }
    }
}

I do not know how you call the method, but this works:我不知道你是如何调用这个方法的,但这有效:

import java.util.ArrayList;

public class Main {

public static void main(String[] args) {
    ArrayList<Object> arrayList = new ArrayList<>();
    Class c = arrayList.getClass();
    search(c, 12);
}

public static void search(Class c, int itemCount) {
    ArrayList<ProductionDate> storage = new ArrayList<>();
    storage.add(new ProductionDate(13));
    storage.add(new ProductionDate(15));
    storage.add(new ProductionDate(11));

    if (storage.getClass() == c) {
        for (ProductionDate d : storage) {
            if (d instanceof ProductionDate &&
                    ((ProductionDate) d).getItemCount() >= itemCount) {
                System.out.println(d);
            }
        }
    }
}


private static class ProductionDate {
    int itemCount;

    public ProductionDate(int itemCount) {
        this.itemCount = itemCount;
    }

    public int getItemCount() {
        return itemCount;
    }

}

} }

output: output:

Main$ProductionDate@5acf9800
Main$ProductionDate@4617c264

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

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