无法将ModuleInfo对象添加到ArrayList
我不确定我是否正确使用generics,但基本上我创建了一个Arraylist moduleList
Arraylist moduleList
和ModuleInfo m
对象,并尝试调用moduleList.add(m)
。 但它不会编译,我收到的错误消息对我来说似乎有点神秘。 错误消息和代码如下。 其他人都知道什么是错的?
void load() { ArrayList moduleList = new ArrayList(); Iterator iter_m; ModuleInfo m; //get modules that depend on this module //retrieve list of all modules and iterate trough each one iter_m = Lookup.getDefault().lookupAll(ModuleInfo.class).iterator(); while(iter_m.hasNext()) { m = iter_m.next(); //loop through modules dependencies and check for a dependency on this module for(Dependency d : m.getDependencies()) { //if found, the module to the list if(d.getName().equals(GmailAuthManager.class.getPackage().getName())) { moduleList.add(m); break; } } } }
错误如下:
error: no suitable method found for add(ModuleInfo) moduleList.add(m); method ArrayList.add(int,CAP#1) is not applicable (actual and formal argument lists differ in length) method ArrayList.add(CAP#1) is not applicable (actual argument ModuleInfo cannot be converted to CAP#1 by method invocation conversion) where CAP#1 is a fresh type-variable: CAP#1 extends ModuleInfo from capture of ? extends ModuleInfo
假设您创建了一个arraylist: –
List extends Animal> list = new ArrayList();
现在,列表引用可以指向ArrayList
或ArrayList
或其他任何内容。 因此,当您尝试将Animal
引用添加到该列表时,编译器不确定该引用实际上是指向在ArrayList
实际Concrete类型中使用的相同implementation
。
例如: – 您可以将指向Cat
的Animal
引用添加到上面的ArrayList中,这是一个灾难。 这就是编译器不允许它的原因。
Animal cat = new Cat(); list.add(cat); // OOps.. You just put a Cat in a list of Dog
您只需创建一个List
,然后可以向其添加任何子类型: –
List newList = new ArrayList (); newList.add(new Cat()); // Ok. Can add a `Cat` to an `Animal` list.
上面的代码有效,因为List
引用只能指向ArrayList
。
因此,在您的示例中,您可以使用: –
List list = new ArrayList();
作为旁注,您应该始终编程interface
而不是implementation
。 所以,总是有你的引用类型的interface
,在这种情况下是List
而不是ArrayList
。
要解决您的问题,请使用:
ArrayList moduleList = new ArrayList ();
这会将您的列表限制为ModuleInfo实例及其子类。