'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);
}
}
}
}
Solution 1:[1]
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);
}
}
}
Solution 2:[2]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | wolfenblut |
| Solution 2 | ChamRun |
