开发者

Bounded generic method not compiling - why?

开发者 https://www.devze.com 2023-03-11 04:21 出处:网络
The code below makes complete sense to me - its about adding an element of some type which is supertype of type T and type S is definitely such a super type , so why the compiler refuses to add \'elem

The code below makes complete sense to me - its about adding an element of some type which is supertype of type T and type S is definitely such a super type , so why the compiler refuses to add 'element' into 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 开发者_Python百科applicable for the arguments (S)
    }
}


Thake an example, if A <- B <- C where <- means that is the supertype, then if S = B and T = C you cannot add an instance of S to a collection of T.

A supertype of T may be the supertype or a subtype of another supertype of T (in this case S).


Collection<? super T> does not mean "a collection that can contain T and any superclass of it" - it's actually not possible to formulate that restriction. What it means is "a collection that can only contain instances of some specific class which is a superclass of T" - basically it ensures that you can add a T to the collection.

The method can be called with a Collection<T>, yet you want to add an S to it.


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


You are trying to put an element of type S into a collection of type T. Generics aren't polymorphic. You have to take notice of 2 problems here. you are trying to create an Collection of type concreteObject extends Object and are adding an object So when you have

Car extends Vehicle{}
ElectricCar extends Car{}

you are trying to do

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

The second problem lies with the non-polymorphism nature of Generics. See this great explanation -> Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

0

精彩评论

暂无评论...
验证码 换一张
取 消