Ste*_*yts 5 java compiler-errors nullpointerexception primitive-types maven
考虑这个课程:
package be.duo.test;
public class Main {
public static void main(String[] args) {
Main main = new Main();
main.execute();
}
private void execute() {
for(int i = 0; i < 10; i++) {
System.out.println("" + method());
}
}
private int method() {
return (Math.random() > 0.5d) ? 1 : null;
}
}
Run Code Online (Sandbox Code Playgroud)
method()具有返回类型int
,它是一种基本类型.
考虑return语句中使用的三元运算符:
[ERROR] error: incompatible types: bad type in conditional expression
[ERROR] <null> cannot be converted to int
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释为什么它表现不同吗?
据我所知,它在 Java 8 下应该是合法的。
\n\n参见表15.25-E。条件表达式类型(参考第三部分第三个操作数):
\n\n3rd \xe2\x86\x92 null\n2nd \xe2\x86\x93 \nint lub(Integer,null)\n
Run Code Online (Sandbox Code Playgroud)\n\nlub(Integer,null)
应该Integer
。基本上,如果您有 形式的条件boolean ? int : null
,则表达式的结果应该是Integer
并且它会被拆箱。(我想你已经知道会发生什么了。)
所以根据规范它应该是相同的。
\n\n看起来像一个编译器错误。已经发现了很多这样的内容,我会说尝试更新到最新版本。
\n 归档时间: |
|
查看次数: |
2481 次 |
最近记录: |