Java三元运算符NPE自动装箱字符串

时间:2014-09-23 13:37:41

标签: java string nullpointerexception ternary-operator autoboxing

这个简单的代码抛出NPE我不明白为什么?

private Boolean isSangByJohnOrPaul()
{
    final String sangBy = "harrison";        
    final Boolean result = sangBy.equals("lennon")?true
            :sangBy //throws NPE at this point
                                    .equals("mccartney")?
                    false
                    :null;        
    return result;
}

我认为问题是由原始类型boolean引起的任何变通方法。?

非常感谢

编辑修复

感谢@Kevin Workman带领我了解这一点。

This is happening because the type return by a ternary operator is the type of the first returned value. In this case, that's the primitive value false. So Java is trying to take the primitive boolean returned by the ternary operator, then use autoboxing to convert it to a wrapper Boolean. But then you return a null from the ternary operator. And then when Java tries to autobox it, it throws an NPE because null can't be autoboxed. You should either use wrapper Booleans as the values in the ternary operator, or restructure this using if statements.

这有效。

private Boolean isSangByJohnOrPaul()
{
    final String sangBy = "harrison";        
    final Boolean result = sangBy.equals("lennon")?Boolean.TRUE
            :sangBy
                                    .equals("mccartney")?
                    Boolean.FALSE
                    :null;        
    return result;
}

我希望帮助某人......

1 个答案:

答案 0 :(得分:1)

false替换为Boolean.FALSE,将true替换为Boolean.TRUE