[英]How can I iterate through an ArrayList of the different class objects to search for a specific class?
如何遍歷不同 class 對象的 ArrayList 以搜索特定的 class?
productionDate 是在基類中實現的接口。
這是代碼,但它不打印任何東西:)
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);
}
}
}
}
首先,刪除第一個 if 語句。
其次,你應該使用實現ProductionDate接口的class來檢查object是否屬於那個特定的class。我認為class在這里是Class c
。
所以:
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);
}
}
}
我不知道你是如何調用這個方法的,但這有效:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.