0

这个简单的代码是抛NPE我不明白为什么?Java三元运算符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工人

编辑固定

感谢这使我这样的理解。

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. 

This works。

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

我希望帮助别人..

+0

发生这种情况,因为三元操作符的类型返回的是*第一个*返回值的类型。在这种情况下,这是原始值false。所以Java试图采用由三元运算符返回的原始布尔值,然后使用自动装箱将其转换为包装布尔值。但是,你从三元运算符返回null。然后,当Java尝试自动复制它时,它会抛出一个NPE,因为null不能被自动装箱。您应该使用包装器布尔值作为三元运算符中的值,或者使用if语句对其进行重构。 – 2014-09-23 13:43:51

+0

看到我编辑的问题..请 – chiperortiz 2014-09-23 13:47:07

+0

很高兴你把它整理出来。当我将这些标记为重复项时,我将上述内容输入为答案,但我认为发布我的内容并不会造成任何负面影响。 – 2014-09-23 13:52:39

回答

1

Boolean.FALSEtrue更换falseBoolean.TRUE