1

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

ziggy
  • 15,677
  • 67
  • 194
  • 287

3 Answers3

4

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>();
Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305
1

Have you tried <? extends Dog> ?

Also can I ask why you are using ArrayList<? super Dog> rather than just ArrayList<Animal>? Perhaps this example is just a simple form of what you are trying to do but it seems inexplicably over complicated.

This is a basic example of generics. Hope it helps.

class Animal{
public sleep(){}
}
class Dog extends Animal{
public sleep(){
    log("Dog sleeps");
}
}
class Rabbit extends Animal{
public sleep(){
    log("Rabbit sleeps");
}
}

class Place<T>{
T animal;
}
class Kennel extends Place<Dog>{
public Kennel(Dog dog){
    super();
    this.animal = dog;
}
}
class Hutch extends Place<Rabbit>{
public Kennel(Rabbit rabbit){
    super();
    this.animal = rabbit;
}
}
Michael Allen
  • 5,712
  • 3
  • 38
  • 63
0

A nice document/introduction about Java Generics can be found here

Robin
  • 36,233
  • 5
  • 47
  • 99