可调用和泛型的集合
我需要在并发线程中启动一堆任务并检索其结果。
这是我的代码:
List<Callable<? extends Object>> tasks = new ArrayList<>();
// Adding some tasks whith return different types of results:
// Callable<Double>, Callable<String>, Callable<SomeOtherType>, and so on...
List<Future<? extends Object>> results = executor.invokeAll( tasks );
但是IDE向我显示了下一个错误:
no suitable method found for invokeAll(List<Callable<? extends Object>>)
method ExecutorService.<T#1>invokeAll(Collection<? extends Callable<T#1>>)
is not applicable
(cannot infer type-variable(s) T#1
(argument mismatch; List<Callable<? extends Object>> cannot be converted
to Collection<? extends Callable<T#1>>
method ExecutorService.<T#2>invokeAll(Collection<? extends Callable<T#2>>,long,TimeUnit)
is not applicable
(cannot infer type-variable(s) T#2
(actual and formal argument lists differ in length))
where T#1,T#2 are type-variables:
T#1 extends Object declared in method
<T#1>invokeAll(Collection<? extends Callable<T#1>>)
T#2 extends Object declared in method
<T#2>invokeAll(Collection<? extends Callable<T#2>>,long,TimeUnit)
方法签名为:
<T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks)
显然,我可以用 替换,并使我的所有任务都返回(例如替换为 )。<? extends Object>
<Object>
Object
SomeTask1 implements Callable<Double>
SomeTask1 implements Callable<Object>
但我的问题是:为什么会发生这个错误?我不明白为什么我不能这样编码。任何人都可以说清楚吗?