This code is from Niko's SCJP Mock Tests (Generics) Q#48
Question is will the above code compile ? yes/no
the answer given is No
However when I tried the following piece of code on my machine it worked perfectly well
The output was
ie the method void say(List<T>) was working like a normal overridden method with runtime polymorphism....
so what gives? is there a typo on the website or what...
BTW I am using Netbeans 6.5 and haven't tried compiling it from the command line.. dont know it that could make a difference...
Also one other thing...
given a collection like List<? extends T> list where T is some concrete type -
Case 1: Retrieving an element from the collection Here we are 100% sure that whatever is returned from the collection IS-A T(ie passes the instanceof test for T). Thus the only object reference that can be on the left hand side of the statement list.get(0) is of type T.Nothing else will do for the compiler irrespective of whether it is legal at runtime or not.
Case 2 - Adding an element to the collection Not possible in this case since there is nothing equivalent to an ArrayStoreException for typed collections. Thus the compiler forbids any modification whatsoever.
However given a collection like List<? super T> list where T is some concrete type -
Case 1: Retrieving an element from the collection Here we are 100% sure that whatever is returned from the collection IS-A Object(ie passes the instanceof test for Object). Thus the only object reference that can be on the left hand side of the statement list.get(0) is of type Object.Nothing else will do for the compiler irrespective of whether it is legal at runtime or not.
Case 2 - Adding an element to the collection Here we can add elements of type T only because a collection typed with type X can accept subtypes of X(direct as well as indirect) as elements.
Also <?> is equivalent to <? extends Object> and hence follows the above rules for extends.
Of course null can be added to the collection in both cases.
Just want to know if my observation is right...
please clarify me if i have missed something or have a misconception..
Thanks in advance
Finally did it!! SCJP 6 certified!!!
Joined: Dec 23, 2008
I tried the code on the command line and it failed to compile because of name clash..
i read the previous discussion on this very topic and the implications of type erasure etc and seem to have got it.
Just want to know if my summing up of rules regarding <? extends T> and <? super T> are correct.