我正在尝试将具体类列表的 future 转换为接口(interface)列表的 future ,但在尝试时出现“不兼容类型”错误。基本上我的代码看起来像这样
public void main()
{
Future<List<ConcreteClass>> future = getFutureStuff();
doStuffWithInferface(future); // Syntax Error!
}
public void doStuffWithInterface(Future<List<InterfaceClass>>)
{
blah();
}
有没有一个好的方法可以在不更改 getFutureStuff 签名的情况下更改此设置
public Future<? extends List<? extends InterfaceClass>> getFutureStuff();
并在我的代码中乱扔 ?扩展InterfaceClass。
最佳答案
getFutureStuff
可以保持不变,但您应该更改 doStuffWithInterface
的签名,因为 future 正在协变使用:
public void doStuffWithInterface(
final Future<? extends List<? extends InterfaceClass>> future
) throws InterruptedException, ExecutionException {
final List<? extends InterfaceClass> list = future.get();
for (final InterfaceClass element : list) {
//use element
}
}
...
Future<List<ConcreteClass>> future = getFutureStuff();
doStuffWithInferface(future); // perfectly fine
关于Java泛型将具体类列表的 future 转换为接口(interface)列表的 future ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18774697/