I am trying to put a subclass object into a List but I am unable to do so because of the compiler error mentioned as a comment. Can someone point out what is the correct way to do this in Java?
public class Animal { }
class Util {
private Map<Class<? extends Animal>, List<? extends Animal>> animalListMap;
public void registerAnimal(Class<? extends Animal> animalClass, Animal animalObject) {
if (animalListMap.containsKey(animalClass)) {
//Append to the existing List
List<? extends Animal> animalList = animalListMap.get(animalObject);
animalList.add(animalObject); //COMPILE ERROR- The method add(capture#3-of ? extends Animal) in the type List<capture#3-of ? extends Animal> is not applicable for the arguments (Animal)
} else {
// and the new entry
List<Animal> vos = new ArrayList<Animal>();
vos.add(animalObject);
animalListMap.put(animalClass, vos);
}
}
}
You cannot add anything to a
List<? extends Animal>
, ever.List<? extends Animal>
means "a list of I-don't-know-what-but-something-that-extends-Animal", which could be aList<Animal>
or aList<Cat>
.If you could, this code would compile:
You can, however, change
List<? extends Animal>
toList<Animal>
which seems to be what you want here.