Search code examples
javageneric-collections

Add parent object to List<? extends Parent> - Java


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);
        }
    }
}

Solution

  • 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 a List<Animal> or a List<Cat>.

    If you could, this code would compile:

    
    List dogs = new ArrayList();
    List animals = dogs;
    animals.add(new Cat());
    Dog dog = dogs.get(0);
    
    

    You can, however, change List<? extends Animal> to List<Animal> which seems to be what you want here.