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);
}
}
}
}
CodePudding user response:
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);
}
}
}
CodePudding user response:
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