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

这个函数会调用自身还是调用重载?

考虑两个重载:

public void add(Integer value)
{
    add(value == null ? null : value.doubleValue());        
}
Run Code Online (Sandbox Code Playgroud)

public void add(Double value)
{
    // some code here
}
Run Code Online (Sandbox Code Playgroud)

如果我用a的null实例调用第一个Integer,那么三元条件是否会调用a的重载Double,或者它是否调用自身?

在我的机器上它调用Double重载,但这是定义良好的Java吗?JLS对此有何评价?

java overloading

11
推荐指数
1
解决办法
1114
查看次数

在编写if-else编译器时会抱怨,但为了速记,它不会,为什么?

在Java中我这样写的时候

public int method(boolean b) {
    if (b)
        return null;
    else
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨incompatible types,但如果用速记替换它

public int method(boolean b) {
    return (b ? null : 0);
}
Run Code Online (Sandbox Code Playgroud)

编译器不会抱怨,而且会有一个NPE.所以我的问题是

  1. 为什么编译器不抱怨
  2. 为什么NPE

java if-statement return nullpointerexception

4
推荐指数
1
解决办法
66
查看次数