【问题标题】:Java ternary Operator NPE autoboxing String [duplicate]Java三元运算符NPE自动装箱字符串[重复]
【发布时间】:2014-11-17 17:57:02
【问题描述】:

这个简单的代码抛出 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;
}

我希望对某人有所帮助..

【问题讨论】:

  • 发生这种情况是因为三元运算符返回的类型是 first 返回值的类型。在这种情况下,这是原始值 false。所以 Java 试图获取三元运算符返回的原始布尔值,然后使用自动装箱将其转换为包装布尔值。但是随后您从三元运算符返回 null 。然后当 Java 尝试对其进行自动装箱时,它会抛出 NPE,因为 null 无法自动装箱。您应该使用包装布尔值作为三元运算符中的值,或者使用 if 语句重新构造它。
  • 请看我编辑的问题..请
  • 很高兴你把它整理好了。当这被标记为重复时,我正在输入上述内容作为答案,但我认为发布我所拥有的内容并没有什么坏处。
  • 非常感谢...我是一名 8 年的 Java 程序员,我从来没有遇到过这样的事情。对不起..你从委内瑞拉学到了一些新的日常问候......
  • 请勿编辑您的答案以在问题文本中写入解决方案。相反,添加一个答案(并反转您的问题编辑)。您可以在 48 小时后将其标记为正确的。

标签: java string nullpointerexception ternary-operator autoboxing


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-27
    • 2014-09-29
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 2020-05-29
    • 2015-03-25
    相关资源
    最近更新 更多