Search code examples
javalistgenericscollectionsbounds

Java list generics with multiple bounds


I'm struggling to understand why the following code doesn't work :

public <E extends Animal & IQuadruped> void testFunction()
{
    List<E> list = new ArrayList<E>();
    Dog var = new Dog();
    list.add(var);
}

with Dog being the following :

public class Dog extends Animal implements IQuadruped
{

}

And I get a compile error on the add :

The method add(E) in the type List<E> is not applicable for the arguments (Dog)

I just want to make sure my list elements extend/implement both classes, and Dog fullfil those conditions, why is it not working ?

Thank you


Solution

  • Generics type erasure is what you are getting. By the time the JVM executes the line where you are adding to the list, the generics is already lost. To get this to work, you would have to do something like:

    public <E extends Animal & IQuadruped> void testFunction(E param) {
        List<E> list = new ArrayList<E>();
        list.add(param);
    }
    
    public void addDog() {
        testFunction(new Dog())
    }