Reputation: 13
I have defined a generic interface that has a supplier and a consumer:
public interface ItemProcessor<T> {
processItem(T task);
T getNextItem();
}
However, I am running into issues when using this interface:
List<ItemProcessor<?>> itemProcessors = new ArrayList<>();
// add itemProcessors to list
for (ItemProcessor<?> itemProcessor : itemProcessors) {
itemProcessor.processItem(itemProcessor.getNextItem());
}
This give me the compile error Required type: capture of ?, Provided type: capture of ?
Since I'm using the same item processor object, shouldn't java be able to infer that the type is the same?
Upvotes: 1
Views: 80
Reputation: 121088
You can hack this a bit, via a so called "wildcard capture method":
private static <T> void process(ItemProcessor<T> item) {
item.processItem(item.getNextItem());
}
And then change your call to:
for (ItemProcessor<?> itemProcessor : itemProcessors) {
process(itemProcessor);
}
I have two answers here and here, for example explaining why this happens. But there is also the official Oracle tutorial explaining things
Upvotes: 1