The limited general method does not compile - why?

The code below has full meaning for me - its about adding an element of some type, which is a supertype of type T and type S, is definitely such a super-type, so why does the compiler refuse to add an element to the collection?

class GenericType<S,T extends S>{
   void add1(Collection<? super T> col ,S element ){
        col.add(element);  // error
       // The method add(capture#9-of ? super T) in the type 
       // Collection<capture#9-of ? super T> is not applicable for the arguments (S)
    }
}
+3
source share
4 answers

Collection<? super T>does not mean β€œa collection that may contain Tany of its superclasses” - in fact, it is impossible to formulate this restriction. This means that β€œa collection that can only contain instances of some particular class that is a superclass T” basically guarantees that you can add Tto the collection.

Collection<T>, S.

+2

, A <- B <- C, <- , , S = B T = C S T.

T T ( S).

+5
new GenericType<Object,Integer>().add1(new ArrayList<Integer>(), "");
+2

S T. . 2 . specificObject, ,

Car extends Vehicle{}
ElectricCar extends Car{}

are you trying to do

Collection<? extends Car> collection;
collection.add(new Vehicle());

The second problem is related to the non-polymorphic nature of Generics. See this wonderful explanation - > Is List <Dog> subclass of List <Animal>? Why are non-specific Java polymorphins implicitly?

0
source

All Articles