gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 12:30:06 28 4
gpt4 key购买 nike

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

我希望能帮助别人..

最佳答案

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

关于Java 三元运算符 NPE 自动装箱字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25996591/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com