I thought I had a good understanding of Java generics.
This code DOES NOT , and I know why.
We can only go to the test method List of types of Animal or its super-type (for example, List of Objects)
package scjp.examples.generics.wildcards; import java.util.ArrayList; import java.util.List; class Animal {} class Mammal extends Animal {} class Dog extends Mammal {} public class Test { public void test(List<? super Animal> col) { col.add(new Animal()); col.add(new Mammal()); col.add(new Dog()); } public static void main(String[] args) { List<Animal> animalList = new ArrayList<Animal>(); List<Mammal> mammalList = new ArrayList<Mammal>(); List<Dog> dogList = new ArrayList<Dog>(); new Test().test(animalList); new Test().test(mammalList);
But here's the weird part (at least for me).
If we declare a class test as general, adding only <T>, then it is COMPILES ! and throws java.lang.ClassCastException:
public class Test<T> { ... }
Exception in thread "main" java.lang.ClassCastException: scjp.examples.generics.wildcards.Animal cannot be cast to scjp.examples.generics.wildcards.Dog
My question is why did adding a generic type <T> type (which is not used anywhere) made the class compile and change the behavior of wildcards?
bary source share