Search code examples
javagenericsscjpocpjp

Java generics - Supertype references


If i have understood generics correctly, a method with parameters declared as <? super T> will accept any reference that is either of Type T or a super type of T. I am trying to test this with the following bit of code but the compiler does not like it.

class Animal{}
class Dog extends Animal{}
class Cat extends Animal{}

class ZiggyTest2{

    public static void main(String[] args){                 

        List<Animal> anim2 = new ArrayList<Animal>();
        anim2.add(new Animal());
        anim2.add(new Dog());
        anim2.add(new Cat());   

        testMethod(anim2);
    }

    public static void testMethod(ArrayList<? super Dog> anim){
        System.out.println("In TestMethod");
        anim.add(new Dog());
        //anim.add(new Animal());
    }
}

Compiler error is :

ZiggyTest2.java:16: testMethod(java.util.ArrayList<? super Dog>) in ZiggyTest2 cannot be applied to (java.util.List<Animal>)
                testMethod(anim2);
                ^
1 error

I dont understand why i cant pass in anim2 since it is of type <Animal> and Animal is a super type of Dog.

Thanks


Solution

  • You are trying to pass an expression of type List<> into a parameter of type ArrayList<>. Not going to work.

    Either this line

    public static void testMethod(ArrayList<? super Dog> anim){
    

    should be

    public static void testMethod(List<? super Dog> anim){
    

    or

        List<Animal> anim2 = new ArrayList<Animal>();
    

    should be

        ArrayList<Animal> anim2 = new ArrayList<Animal>();