Sorry if the title seems confusing, but some examples are in order.
Let\'s say I have some Java class with a generic type parameter:
public class Gen
The problem your facing is denominated Covariance.
List<GenericClass<String>> stringy = ...
List<GenericClass<?>> generic = stringy;
generic.add(new GenericClass<Integer>());
If this wasn't a compile error, then the last line of code would be possible.
You could get around the error by doing this:
List<? extends GenericClass<?>> generic = stringy;
but you can not use add
also because you don't really know what ? extends GenericClass<?>
is (Covariance once again). In this case you can only enumerate through the List and expect GenericClass<?>
.
Technically, that's because List<GenericClass<String>>
is not a subtype of List<GenericClass<?>>
. In order to make it work, you could do something like
List<? extends GenericClass<?>> generic = stringy
which should work as expected (though is pretty ugly...).
See, for example, this SO question for more details