简体   繁体   中英

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?

productionDate is an interface that is implemented in base classes.

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.

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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