Why can't a Generic type containing a Generic type be assigned to a Generic typed class of wildcard type

前端 未结 2 1525
栀梦
栀梦 2021-01-02 11:03

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         


        
相关标签:
2条回答
  • 2021-01-02 11:12

    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<?>.

    0 讨论(0)
  • 2021-01-02 11:27

    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

    0 讨论(0)
提交回复
热议问题