This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I've encountered the following code in the OCJP mock test from the K&B study guide book attached CD, and I think this is not covered in the Study Guide:
I'm really not getting why you should write ? extends T or ? super T. What are the implications? T is defined nowhere?
? super Cat makes sense to me. This implies that you can add Cats to the list passed in.
? extends Animal also makes sense. This implies you can iterate any incoming list using the Animal object type.
You need to read up on generics -- specifically, generic methods. The T type is determined by the compiler when the method is used -- it is determined at compile time, but not during the compilation of this code.
As for "? extends" and "? super", those are wildcards. And the "implication" is that with wildcards you can write methods that support more parameter types. In general, if you have methods where you don't really care too much of the type (and can operate without knowing the type too much), you should use wildcards, as it allows your method to be more applicable.
Jim Pouwels wrote:Still unclear to me. Say I have the following code:
As far as I know I can still pass a list with any generic type. Where is the restriction? What invocation will fail in this case?
You can pass any type, because that is how you used it... let's say you actually use the returned list, and assigned it to a list of animals. In that case, T will be typed as Animal. And your method will work for Cat, if it had been the wildcard that extends T.
If you didn't use wildcards, or use the version that allows the "super", you would have gotten a compilation error.