null != null - 关于如何重新安排代码或防止这种情况的任何想法?
目前正在调试,发现一个 if 语句,没有(我认为......)原因给了我一个 NPE,显然是有原因的。该语句似乎是 if(false && (null != null || null != Color))
。
if(destination != null && (destination.getPiece() != null || destination.getPiece().getColour() !=pieceColour))
- if 语句
两个目标 < em>可以为空,而碎片可以为。 getColour() 方法从piece 返回一个Color 类型的属性,如果该piece 为null,则该属性必须为null。目标处的片段具有与 if 语句中的片段颜色不同的属性。
具体来说,如何重新排列 (destination.getPiece() != null) ?
Currently debugging, and found an if-statement which for no (I thought...) reason gave me an NPE, obviously for a reason. Which seemed to be that the statement turned out to be if(false && (null != null || null != Color))
.
if(destination != null && (destination.getPiece() != null || destination.getPiece().getColour() != pieceColour))
- the if-statement
Both destination can be null and piece can be. The getColour() method returns an attribute of type Color from piece, which must be null if the piece is null. The piece at destination has a different pieceColour attribute then the one in the if-statement.
Specifically, how do I re-arrange (destination.getPiece() != null) ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
该声明第二部分的逻辑非常混乱。
如果
getPiece()
为 null,则getPiece().getColour()
无效,反之亦然。换句话说,destination.getPiece() == null => destination.getPiece().getColour() 是一个 NPE。
同样,
destination.getPiece().getColour()
是任何东西 =>destination.getPiece() != null
对我来说唯一有意义的是:
也就是说,目的地不为空,并且该块要么为空,要么为不同的颜色。
The logic in the second part of the statement is very confused.
getPiece().getColour()
is not valid ifgetPiece()
is null and vice-versa.In other words,
destination.getPiece() == null => destination.getPiece().getColour()
is a NPE.Similarly,
destination.getPiece().getColour()
being anything =>destination.getPiece() != null
Only thing that makes sense to me is:
That is, the destination is not null, and either the piece is null or a different color.
其他答案也有效,但为了清楚起见,我建议将
destination.getPiece()
的结果存储在局部变量中:Other answers work but for clarity I'd suggest storing the result of
destination.getPiece()
in a local variable:如果
obj 为 null
则 (obj != null) 返回 false,但在检查 obj.getColor() 时将抛出 NullPointerException。这就是为什么,它应该是这样的:if
obj is null
then (obj != null) return false but while checking obj.getColor() will throw NullPointerException. That is why, it should be like this :最简单的答案是将其分成两个 if 语句:
The simplest answer would be to split this into two if statements:
应该是:
Should be: