1

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?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183

1 Answers1

1

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

Eugene
  • 117,005
  • 15
  • 201
  • 306