invokeAll()不愿意接受Collection< Callable< T>> [英] invokeAll() is not willing to accept a Collection<Callable<T>>
问题描述
我无法理解为什么这段代码无法编译
I fail to understand why this code won't compile
ExecutorService executor = new ScheduledThreadPoolExecutor(threads);
class DocFeeder implements Callable<Boolean> {....}
...
List<DocFeeder> list = new LinkedList<DocFeeder>();
list.add(new DocFeeder(1));
...
executor.invokeAll(list);
错误信息是:
The method invokeAll(Collection<Callable<T>>) in the type ExecutorService is
not applicable for the arguments (List<DocFeeder>)
list
是 Collection
DocFeeder
,它实现了 Callable< Boolean>
- 发生了什么?!
list
is a Collection
of DocFeeder
, which implements Callable<Boolean>
- What is going on?!
推荐答案
只是为了扩展saua的答案......
Just to expand on saua's answer a little...
在Java 5中,方法是声明为:
In Java 5, the method was declared as:
invokeAll(Collection<Callable<T>> tasks)
在Java 6中,该方法声明为:
In Java 6, the method is declared as:
invokeAll(Collection<? extends Callable<T>> tasks)
通配符差别非常大重要 - 因为列表< DocFeeder>
集合<?扩展Callable< T>>
但它不 Collection< Callable< T>>
。考虑一下这种方法会发生什么:
The wildcarding difference is very important - because List<DocFeeder>
is a Collection<? extends Callable<T>>
but it's not a Collection<Callable<T>>
. Consider what would happen with this method:
public void addSomething(Collection<Callable<Boolean>> collection)
{
collection.add(new SomeCallable<Boolean>());
}
这是合法的 - 但如果你能打电话给 addSomething
带有列表< DocFeeder>
,因为它会尝试将非DocFeeder添加到列表中。
That's legal - but it's clearly bad if you can call addSomething
with a List<DocFeeder>
as it will try to add a non-DocFeeder to the list.
因此,如果您遇到Java 5,则需要从列表< Callable< Boolean>>
>列表< DocFeeder> 。
So, if you are stuck with Java 5, you need to create a List<Callable<Boolean>>
from your List<DocFeeder>
.
这篇关于invokeAll()不愿意接受Collection< Callable< T>>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!