Suppose you create an arraylist as: -
List<? extends Animal> list = new ArrayList<Dog>();
Now that list reference can point to an ArrayList<Dog>
or an ArrayList<Cat>
or whatever. So, when you try to add an Animal
reference to that list, compiler is not sure that, that reference is actually pointing the same implementation
that is used in actual Concrete type of ArrayList
.
For e.g.: - You might add an Animal
reference pointing to Cat
into the above ArrayList, which is a disaster. That's why Compiler does not allow it.
Animal cat = new Cat();
list.add(cat); // OOps.. You just put a Cat in a list of Dog
You can rather just create a List<Animal>
, and you can add any subtype to it: -
List<Animal> newList = new ArrayList<Animal>();
newList.add(new Cat()); // Ok. Can add a `Cat` to an `Animal` list.
The above code works because, a List<Animal>
reference can only point to an ArrayList<Animal>
.
So, in your example, you can use: -
List<ModuleInfo> list = new ArrayList<ModuloInfo>();
As a side note, you should always program to interface
rather than implementation
. So, always have your reference types of interface
, in this case List
rather than ArrayList
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…