Bhaskar
Bhaskar

Reputation: 7523

Bounded generic method not compiling - why?

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

Upvotes: 3

Views: 178

Answers (4)

jelle
jelle

Reputation: 770

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?

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

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

Upvotes: 2

Kru
Kru

Reputation: 4235

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

Upvotes: 5

Michael Borgwardt
Michael Borgwardt

Reputation: 346260

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.

Upvotes: 2

Related Questions