Raw types, unbounded wilcard and bounded wildcard

泄露秘密 提交于 2019-12-10 10:29:33

问题


I have a quick question as below: Here's a simple examples about this whole issues:

List a = new ArrayList();
List <?> b;
List <? extends Object> c;

According to Java SCJP by khalid mughal (a very good book!):

a = b; // ok. Widening conversion.
b = a; // ok too. No unchecked warning.

b = c; // ok
c = b; // ok

c=a; // ok but now will issue a unchecked warning. // clause 1

I do understand that any raw types (example a) when assigned to any bounded wilcard references, a unchecked warning is issues (since the content in that raw type a could be anything).

My questions is since c is the highest upper bound (? extends objects), shouldn't a be able to assigned to c without that warning?


回答1:


If I understand your question correctly (and I really don't think I do), there appear to be two instances in which interaction with raw types could cause an unchecked warning to occur, according to this page:

  • An invocation of a method or constructor of a raw type generates an unchecked warning if erasure changes any of the types of any of the arguments to the method or constructor.
  • An assignment to a field of a raw type generates an unchecked warning (§5.1.9) if erasure changes the field's type.

So the answer to your question basically seems to be "erasure could result in unchecked warnings in the presence of raw types". As far as I can tell, this is most likely to occur when nested types are used - I can't see anywhere else in the definition of erasure that would likely cause a type to change, but perhaps someone else can suggest whether that is or isn't the source of this.



来源:https://stackoverflow.com/questions/3489947/raw-types-unbounded-wilcard-and-bounded-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!