Understanding wildcards in Java generics

后端 未结 7 1603
不思量自难忘°
不思量自难忘° 2020-12-31 11:07

I\'m not sure why the last statement in the following code is illegal. Integer should be a subtype of ?, so why can\'t I assign it to b

相关标签:
7条回答
  • 2020-12-31 12:07

    The point is that b refers to a list of some type, but the compiler doesn't know what the type is, so it doesn't know whether or not it's valid to add an Integer to it. And a good thing too, given your example - you'd be adding an Integer to an object initially created to hold a list of strings. Sure, that information is lost at execution time in Java - but the compiler tries to keep you as safe as it can.

    See the Java generics FAQ for a lot more information.

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