java三元条件奇怪的空指针异常 [英] java ternary conditions strange null pointer exception

查看:140
本文介绍了java三元条件奇怪的空指针异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能解释一下为什么在第一种情况下检测到空指针,但在另一种情况下没有?

Can someone explain me why in the first case null pointer was detected, but no on the other ?

也许他总是看第一种类型,但为什么他仅在条件为假时才这样做..

Maybe he always looks on the first type, but why he does so only if the condition is false..

@Test
public void test1() {
    final Integer a = null;

    final Integer b = false ? 0 : a;

    //===> NULL POINTER EXCEPTION
}

@Test
public void test2() {
    final Integer b = false ? 0 : null;

    //===>NOT NULL POINTER EXCEPTION
}

@Test
public void test3() {
    final Integer a = null;

    final Integer b = true ? 0 : a;

    //===>NOT NULL POINTER EXCEPTION
}

@Test
public void test4() {
    final Integer a = null;

    final Integer b = false ? new Integer(0) : a;

    //===> NOT NULL POINTER EXCEPTION
}

@Test
public void test5() {
    final Integer a = null;

    final Integer b = false ? a : 0;

    //===>NOT NULL POINTER EXCEPTION
}


推荐答案

当你使用三元运算符时,

When you use ternary operator,

 flag  ? type1 : type2

转换时Type1和type2的类型必须相同。首先它实现type1然后实现type2。

Type1 and type2 must be of same type while conversion. First it realises type1 and then type2.

现在看看你的案例

 final Integer b = false ? 0 : a;

由于 type1 0 并且它需要作为原语,因为 a 正在尝试将其转换为原语。因此空指针。

Since type1 is 0 and it takes as a primitive and since a is trying to convert it as a primitive. Hence the null pointer.

同样棘手的test5

where as same tricky test5

 final Integer b = false ? a : 0;

由于a类型为整数 0已装箱包装整数并分配给LHS。

Since a is of type Integer 0 boxed to wrapper integer and assigned to the LHS.

这篇关于java三元条件奇怪的空指针异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆