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