I was solving a mock question of Generics from JavaBeat. The code snippet is given below
It was asked that what are the legal calls for the generic method. All methods except the second call compile.
When i saw the explanation it is written that, call 2 won't work because the compiler cannot guarantee the type
to substitute. I am unable to understand this statement. Can someone explain.
The method call only allows Collections holding Object instances - not any subtypes of Object - Objects only. This is where generics doesn't do polymorphism on its types.
In the first code (List<? super Object>), you are saying List can contain Object or any class that is a super type of Object (which is none). So that works.
In the second piece of code (List< ? extends Object>), you are declaring a List that can hold Object instances and anything that extends Object (which is everything) and then trying to call the method. That's the reason for the compiler error. The method will only accept a Collection with Object instances.
In the third piece of code (List<Object> ls3) List can only contain Object instances so that works.
The fourth piece of code is the same as the first one.