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

Java的简写形式当其中一个返回的对象为null时,If语句返回NullPointerException

为什么此代码返回错误:java.lang.NullPointerException

Object obj = null;
Long lNull = null;
Long res = obj == null ? lNull : 10L;
Run Code Online (Sandbox Code Playgroud)

但是以下方式可以正常运行:

Object obj = null;
Long res = obj == null ? null : 10L;
Run Code Online (Sandbox Code Playgroud)

java null if-statement nullpointerexception

7
推荐指数
1
解决办法
395
查看次数

带有 Optional 的三元运算符中不需要的空指针异常

据我了解,以下代码不应抛出,Null Pointer exception因为我正在安全地使用 Optional 接口。

但是,当我运行此代码时,它会抛出NPE.

public class Test {
        public static void main(String[] args) {
            final Integer inte = false ? 0 : Optional.ofNullable((Integer) null).orElse(null);
         }
    }
Run Code Online (Sandbox Code Playgroud)

如果我在代码中的某个地方弄错了,请告诉我并帮助我纠正相同的错误。

java optional java-8

-3
推荐指数
1
解决办法
199
查看次数