什么时候不应该使用Java快捷键运算符& [英] When should I not use the Java Shortcut Operator &

查看:50
本文介绍了什么时候不应该使用Java快捷键运算符&的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,使用&&作为Java中的数学运算,如果评估的LHS(左手边)失败,则不会检查右手边.

My understanding is that when using && as an mathematical operation in Java, if the LHS (Left Hand Side) of an evaluation fails, the right hand side will not be checked, so.

false && getName();

getName()永远不会被调用,因为LHS已经失败了.

getName() would never be called as the LHS has already failed.

false & getName();

如果我知道LHS失败了,我什么时候想检查RHS?当然,对RHS评估的任何依赖都将是不良的编码习惯吗?

When would I ever want to check the RHS if I know the LHS has failed? Surely any dependency on the RHS evaluation being ran would be bad coding practice?

谢谢

推荐答案

& &&的原因不是,那就是正确评估一侧,而另一侧则没有.

Well the reason for & and && is not, that one evaluates the right side and the other doesn't.

  • & 按位运算符,它对两个值进行按位与.它返回一个值.

  • & is a bitwise operator, which makes a bitwise AND of the two values. It returns a value.

理论上,如果左侧的所有位均为0(如 false 的情况),则不必评估右侧.我想这是在每种情况下都要对其进行评估的设计决定.在简单的情况下,这比检查左侧是否为0更快.

Theoretically, if all bits of the left side are 0 (as is the case for false), the right side must not neccessarily be evaluated. I guess it's a design decision that it is evaluated in every case. In the simple cases, it is faster than checking if the left side is 0.

&& 条件逻辑运算符,它接受两个布尔值并返回一个布尔值(如果满足,则为 true 并且仅当双方均为 true 时).

&& is a conditional logical operator, which takes two booleans and returns a boolean (that is true if and only if both sides are true).

此处同样适用,如果左侧为 false ,则无需检查右侧.在这种情况下,决定跳过这种情况下对右侧的评估.

The same applies here, if the left side is false, we don't need to check the right side. Here the decision was taken to skip the evaluation of the right side in that case.

并回答您的最后一个问题(如果LHS失败,您何时要评估RHS),在某些情况下可以解决.但是,在任何情况下都可以避免这些情况(请参阅 jocelyn的答案,以确保这两个表达式被评估)而不会降低可读性.实际上,我认为jocelyn的方法比 if(exprA()&r exprB()){...} 更具可读性.

And to answer your last question (when would you want to evaluate the RHS if the LHS has failed), there are some scenarios where it can be ok. However, in any case it is possible to prevent these situations (see jocelyn's answer for a good way to make sure that both expressions are evaluated) without loosing readability. In fact, I think jocelyn's way is more readable than if (exprA() & exprB()) { ... }.

我个人从不使用& ,除非我真的需要按位AND.

Personally I never use & unless I really need a bitwise AND.

这篇关于什么时候不应该使用Java快捷键运算符&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆