Cannot add ModuleInfo object to ArrayList <? extends ModuleInfo>

I'm not sure whether using generic correctly, but basically I created objects Arraylist<? extends ModuleInfo> moduleListand ModuleInfo mand tried to call moduleList.add(m). However, it will not compile, and I get an error message that seems a little cryptic to me. Error message and code below. Does anyone else know what is wrong?

void load() {
    ArrayList<? extends ModuleInfo> moduleList = new ArrayList();
    Iterator<? extends ModuleInfo> 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;
            }
        }
    }
}

The error is as follows:

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
+2
source share
2 answers

Suppose you created an arraylist as: -

List<? extends Animal> list = new ArrayList<Dog>();

ArrayList<Dog> ArrayList<Cat> . , Animal , , implementation, ArrayList.

, : - Animal, Cat ArrayList, . .

Animal cat = new Cat();
list.add(cat);  // OOps.. You just put a Cat in a list of Dog

List<Animal>, : -

List<Animal> newList = new ArrayList<Animal>();
newList.add(new Cat());  // Ok. Can add a `Cat` to an `Animal` list.

, List<Animal> ArrayList<Animal>.


, : -

List<ModuleInfo> list = new ArrayList<ModuloInfo>();

interface, implementation. interface, List, ArrayList.

+10

, :

ArrayList<ModuleInfo> moduleList = new ArrayList<ModuleInfo>();

ModuleInfo, .

+1

All Articles