相关疑难解决方法(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万
查看次数

为什么我可以在三元操作中将原始类型设置为null

我一直以为Java中的原始类型不可能null,因为如果我尝试这样做,这是一个编译时错误:

int test = null;
Run Code Online (Sandbox Code Playgroud)

但是在三元操作中,似乎允许:

int test = something != 0 ? 5 : null;
Run Code Online (Sandbox Code Playgroud)

不是三元操作(在这种情况下):

int test;
if (something != 0){
    test = 5;
} else {
    test = null
}
Run Code Online (Sandbox Code Playgroud)

这当然不应该被允许.如果该条件失败,它将自动抛出一个NullPointerException由于自动装箱.那么为什么java编译器不会像这样获取废话呢?

java null ternary-operator raw-types

12
推荐指数
1
解决办法
983
查看次数

lub(null,Double)是什么?

JLS版本8中的表15.25-B表示条件表达式的类型

true ? null : 0.0
Run Code Online (Sandbox Code Playgroud)

是的lub(null,Double),4.10.4节lub似乎是一些疯狂的难以理解的事情.

这看起来与Double某种类型的类型不同,或者它们可能只是编写Double,就像它们在表中的其他地方所做的那样.但不清楚差异可能是什么.我试图从第4.10.4节开始研究它,但到了我接触到的部分时

让lub(U1 ... Uk)成为:

最佳(W1)&...&Best(Wr)

看起来他们说这种类型是null和Double类型的交集类型,这没有任何意义.

什么是lub(null, Double)?具有此类型的条件表达式与其类型刚刚定义为不同的行为有何不同Double

java types language-lawyer

8
推荐指数
2
解决办法
481
查看次数