为什么这个通用代码会编译?(Why does this generic code compile?)

编程入门 行业动态 更新时间:2024-10-23 11:21:46
为什么这个通用代码会编译?(Why does this generic code compile?) <X> X foo(List<? super X> list) { return null; } void test() { List<Number> list = ...; String s1 = this.foo(list); // huh? }

最后一行没有任何意义,javac怎么允许呢?

现在, foo()方法也没有意义; 它必须返回null,没有其他值可以以类型安全的方式返回。 因此,运行时的最后一行不会导致任何问题:它为String变量赋值null。

静态地,为什么最后一行编译? ( javac 1.6 u21 b06

<X> X foo(List<? super X> list) { return null; } void test() { List<Number> list = ...; String s1 = this.foo(list); // huh? }

The last line doesn't make any sense, how could javac allow it?

Now, the foo() method doesn't make sense either; it must return null, there is no other value that can be returned in a type safe manner. Therefore the last line at runtime will not cause any problem: it assign a null to a String variable.

Still, statically, why does the last line compile? (javac 1.6 u21 b06)

最满意答案

代码不会使用下一个JDK版本1.6.0_22-b04进行编译。 错误是:

类型不匹配:无法从Number转换为String

我想你对编译器错误的建议可能是真的。

The code won't compile with the next JDK version 1.6.0_22-b04. Error is:

Type mismatch: cannot convert from Number to String

I guess your suggestion of a compiler bug may be true.

更多推荐

本文发布于:2023-07-04 11:06:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1023589.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:代码   generic   compile   code

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!