invokeAll() 不愿意接受 Collection>;
我无法理解为什么这段代码无法编译
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
是 DocFeeder
的 Collection
,它实现了 Callable< ;Boolean>
- 发生了什么?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只是为了稍微扩展 saua 的答案...
在 Java 5 中,该方法声明为:
在 Java 6 中,该方法声明为:
通配符差异非常重要 - 因为
List
是一个集合<? 扩展了 Callable>
,但它不是Collection>
。 考虑使用此方法会发生什么:这是合法的 - 但如果您可以使用
List
调用addSomething
,这显然很糟糕,因为它会尝试添加非 DocFeeder到列表中。因此,如果您坚持使用 Java 5,则需要从
List
创建一个List>
。Just to expand on saua's answer a little...
In Java 5, the method was declared as:
In Java 6, the method is declared as:
The wildcarding difference is very important - because
List<DocFeeder>
is aCollection<? extends Callable<T>>
but it's not aCollection<Callable<T>>
. Consider what would happen with this method:That's legal - but it's clearly bad if you can call
addSomething
with aList<DocFeeder>
as it will try to add a non-DocFeeder to the list.So, if you are stuck with Java 5, you need to create a
List<Callable<Boolean>>
from yourList<DocFeeder>
.该代码在 Java 6 中编译得很好,但在 Java 5 中编译失败,给出
然而改变
list
像这样:使它在 Java 5 和 Java 6 上工作。
That code compiles perfectly fine with Java 6, but fails to compile with Java 5 giving
However changing the
list
like this:Makes it work on both Java 5 and Java 6.
感谢您的详细回答,但它仍然让我烦恼 - Callable 是一个接口,所以实际上,乔恩答案中的“addSomething”函数应该没问题(不仅合法,而且合理) - 因为,这就是接口的全部要点- 只要您遵守一些初始协议,我不在乎您将哪个对象添加到列表中。 我认为,您提出的问题应该在不同的范围内解决。
除此之外,事实仍然是代码没有编译 - 它应该......
Thanks for the detailed answer , but it still bugs me - Callable is an interface , so actually , the "addSomething" function in Jon's answer should be OK (not only legal , but reasonable) - because , well , that's the whole point of interfaces - As long as you comply with some initial agreement , I don't care which object you'd add to the list. imo , the problem you presented should be addressed on a different scope.
Besides that , the fact remains that the code didn't compile - and it should have...