带和不带 () 的条件运算符
当我想打印我的一个对象(显然不为空)时,我遇到了一些奇怪的事情。
如果我使用这一行:
text.append("\n [ITEM ID]: " + (item == null ? (otherItem == null ? 0 : otherItem .getItems().get(i).getId()) : item .getItems().get(i).getId()));
如果我的 item
对象为 null
,则不会出现空指针异常。当然这应该是例外的结果。但是如果我在没有 ()
标记的情况下使用它:
text.append("\n [ITEM ID]: " + item == null ? (otherItem == null ? 0 : otherItem .getItems().get(i).getId()) : item .getItems().get(i).getId())
我认为条件运算符不会执行运算符的其他部分,但我得到了 NullPointerException。
如果有人向我解释为什么在这种情况下使用 ()
标记至关重要,我将不胜感激。
I have run in to some weird thing when I want to print one of my objects (which is obviously not null).
If I use this line:
text.append("\n [ITEM ID]: " + (item == null ? (otherItem == null ? 0 : otherItem .getItems().get(i).getId()) : item .getItems().get(i).getId()));
There is no null pointer exception if my item
object is null
. Of course this should be the excepted result. But if I use it without the ()
marks:
text.append("\n [ITEM ID]: " + item == null ? (otherItem == null ? 0 : otherItem .getItems().get(i).getId()) : item .getItems().get(i).getId())
I thought the conditional operator does not execute the other part of the operator, but I got a NullPointerException.
I would appreciate if someone explain it to me, why it is essential to use the ()
marks in this case.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果不添加括号,则
"\n [ITEM ID]: "
和item
之间的串联将优先进行相等测试和条件运算符(请参阅Java 运算符中的优先级),因此如果您希望它工作,则必须将它们放入(如 <代码>("\n [ITEM ID]: " + item) == null 可能不是您想要评估的)。The concatenation between
"\n [ITEM ID]: "
anditem
will have priority on the equality test and the conditional operator if you don't put the parenthesis (see the precedences in Java operators), so you have to put them if you want it to work (as("\n [ITEM ID]: " + item) == null
is probably not what you want to evaluate).+
运算符的优先级高于? :
,所以你确实需要使用括号。请参阅http://bmanolov.free.fr/javaoperators.phpThe
+
operator has higher precedence than? :
, so you do need to use parenthesis. See http://bmanolov.free.fr/javaoperators.php