Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bounded generic method not compiling - why?

Tags:

java

generics

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 applicable for the arguments (S)
    }
}
like image 438
Bhaskar Avatar asked Jan 31 '26 12:01

Bhaskar


2 Answers

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).

like image 58
Kru Avatar answered Feb 03 '26 02:02

Kru


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.

like image 40
Michael Borgwardt Avatar answered Feb 03 '26 01:02

Michael Borgwardt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!