通用转型问题

huangapple go评论82阅读模式
英文:

Generic Casting Issue

问题

我定义了一个通用接口,其中包含供应商和消费者:

public interface ItemProcessor<T> {
    void processItem(T task);
    T getNextItem();
}

然而,在使用这个接口时我遇到了问题:

List<ItemProcessor<?>> itemProcessors = new ArrayList<>();

// 将 itemProcessors 添加到列表中

for (ItemProcessor<?> itemProcessor : itemProcessors) {
    itemProcessor.processItem(itemProcessor.getNextItem());
}

这给我带来了编译错误:所需类型:? 的捕获,提供的类型:? 的捕获。由于我正在使用同一个 item processor 对象,Java 不应该能够推断出类型是相同的吗?

英文:

I have defined a generic interface that has a supplier and a consumer:

public interface ItemProcessor&lt;T&gt; {
    processItem(T task);
    T getNextItem();
}

However, I am running into issues when using this interface:

List&lt;ItemProcessor&lt;?&gt;&gt; itemProcessors = new ArrayList&lt;&gt;();

// add itemProcessors to list

for (ItemProcessor&lt;?&gt; 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?

答案1

得分: 1

你可以通过所谓的“通配符捕获方法”来稍微修改这个代码:

private static <T> void process(ItemProcessor<T> item) {
    item.processItem(item.getNextItem());
}

然后将调用更改为:

for (ItemProcessor<?> itemProcessor : itemProcessors) {
    process(itemProcessor);
}

我在这里有两个答案这里这里,例如解释了为什么会发生这种情况。但也可以参考官方的 Oracle 教程来了解更多信息

英文:

You can hack this a bit, via a so called "wildcard capture method":

private static &lt;T&gt; void process(ItemProcessor&lt;T&gt; item) {
    item.processItem(item.getNextItem());
}

And then change your call to:

for (ItemProcessor&lt;?&gt; 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

huangapple
  • 本文由 发表于 2020年10月22日 00:52:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/64468239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定