Bounded generic method not compiling - why?

Collection 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, yet you want to add an S to it.

– Bhaskar Jun 7 at 12:07 @Bhaskar: the wildcard also allows you to call the method with a Collection or a Collection - everything you can add a T to. – Michael Borgwardt Jun 7 at 12:20.

– Bhaskar Jun 7 at 12:11 correct answer indeed , but have to give it to Michael for letting me understand it in prose. – Bhaskar Jun 7 at 12:32.

1 for a valid concrete and unsafe example. Though it might be more clear that you're exercising the "super" keyword if you passed in an ArrayList. Using ArrayList does show the most obvious flaw in the OP's reasoning, in that List admits a List which obviously won't accept an arbitrary supertype of T.

– Mark Peters Jun 7 at 12:23 +1 for the terse and accurate code bringing out the defect – Bhaskar Jun 7 at 12:33.

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 collection; collection. Add(new Vehicle()); The second problem lies with the non-polymorphism nature of Generics. See this great explanation -> Is `List` a subclass of `List`?

Why aren't Java's generics implicitly polymorphic?

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions