相关疑难解决方法(0)

将null返回为允许使用三元运算符的int,而不是if语句

让我们看看以下代码段中的简单Java代码:

public class Main {

    private int temp() {
        return true ? null : 0;
        // No compiler error - the compiler allows a return value of null
        // in a method signature that returns an int.
    }

    private int same() {
        if (true) {
            return null;
            // The same is not possible with if,
            // and causes a compile-time error - incompatible types.
        } else {
            return 0;
        }
    }

    public static void main(String[] args) {
        Main m = …
Run Code Online (Sandbox Code Playgroud)

java autoboxing nullpointerexception conditional-operator

185
推荐指数
5
解决办法
2万
查看次数