Disclaimer: I'm not a professional developer, and I'm not intending to become one. Reading book about Java, as I wanted to try Android programming, no previous Java experience whatsoever.
I'm reading this book - and I rather like it. I've read part of chapter about generic classes, got to the point where they mention wildcards, and got confused.
If B extends A:
List<B>
is not a subtype ofList<A>
(as I understand it they're exactly the same)List<? extends B>
is a subtype ofList<? extends A>
The latter allows for writing functions that accept arguments that are of generic type - for example List<? extends A>
. Such function would accept an argument of either List<B>
or List<A>
.
Now, for my question:
Wouldn't it be simpler to implement generics in a manner similar to C++ (in a "template" flavour)? This would make List<B>
and List<A>
two separate types, that would be related in expected way. This would also allow to simply state in a function that you expect an argument to be of type List<A>
, which would allow List<B>
to fit there just fine.
I'm guessing there was more than "we hate C++, let's make things different" behind this :) It's also quite possible that I don't know something yet, that makes wildcards a fantastic and useful tool. What's your take on this?
Edit: if you're mentioning List<X>
in your answer, remember to use backticks, to avoid <X>
being interpreted as HTML tag.