我的问题如下:
我有一个执行器,它在自定义对象的数组列表上运行一些长时间运行的任务。 我希望能够为执行器提供不同类类型的 Arraylists,每个类类型都实现一个接口(interface),以便执行器知道如何处理任何兼容的类实例。
class MyExectorService{
....
interface MyInterface{
String getData();
}
}
class A implements MyExecutor.MyInterface {} ....
class B implements MyExecutor.MyInterface {} ....
我的执行器单例有一个方法签名:
public void submitList(ArrayList<MyInterface> list, ....)
当我有 A 类或 B 类等的 ArrayList 时,我从编译器中得到错误的参数类型异常。我可以创建一些只返回 ArrayList 原始类型的函数,以便在提交之前对其进行转换
例如
public static ArrayList getRaw(ArrayList list){
return list;
}
...MyExecutorService.getInstance().submitList(getRaw(aa /* arraylist of class A /*),...)
但是正确的方法是什么?
最佳答案
您的 submitList
方法严格需要一个泛型类型为 MyInterface
的数组列表。这与泛型类型是 MyInterface 的某些子类型的数组列表不同。您可以将其更改为:
private void submitList(List<? extends MyInterface> list, ...)
这指定第一个参数必须是一个列表,其泛型类型是MyInterface
的某种子类型。另外,一般情况下,建议接受 List
而不是 ArrayList
作为参数(即 program to an interface ),因为大多数时候,您并不关心哪种实现调用该方法时,您将获得 List
的列表。
关于java - ArrayList 泛型 : interface inside diamond,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40613791/