原始类型、无界通配符和有界通配符

发布于 2024-09-14 03:29:30 字数 516 浏览 2 评论 0原文

我有一个简单的问题如下: 这是关于整个问题的一个简单示例:

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

根据 khalid mughal 的 Java SCJP(一本非常好的书!):

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

我确实理解,当分配给任何有界通配符引用时,任何原始类型(示例 a)都会出现未经检查的警告(因为原始类型 a 中的内容可以是任何内容)。

我的问题是,既然 c 是最高的上限(?扩展对象),那么 a 是否应该能够在没有警告的情况下分配给 c ?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

淤浪 2024-09-21 03:29:30

如果我正确理解你的问题(我真的不认为我理解),根据 此页面

  • 如果擦除更改了方法或构造函数的任何参数的任何类型,则调用原始类型的方法或构造函数会生成未经检查的警告。
  • 如果擦除更改了字段的类型,则对原始类型字段的赋值会生成未经检查的警告 (§5.1.9)。

所以你的问题的答案基本上似乎是“擦除 在存在原始类型的情况下可能会导致未经检查的警告”。据我所知,这种情况最有可能在使用嵌套类型时发生 - 我在擦除的定义中看不到任何可能导致类型更改的其他地方,但也许其他人可以建议这是否是或不是这个的来源。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文