Java &= 运算符是否适用 &或&&?
假设
boolean a = false;
我想知道 do:
a &= b;
是否等于
a = a && b; //logical AND, a is false hence b is not evaluated.
或另一方面意味着
a = a & b; //Bitwise AND. Both a and b are evaluated.
Assuming
boolean a = false;
I was wondering if doing:
a &= b;
is equivalent to
a = a && b; //logical AND, a is false hence b is not evaluated.
or on the other hand it means
a = a & b; //Bitwise AND. Both a and b are evaluated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
来自 Java 语言规范 - 15.26 .2 复合赋值运算符。
因此
a &= b;
相当于a = a & b;
。(在某些用法中,类型转换会对结果产生影响,但在这种情况下,
b
必须是boolean
并且类型转换不执行任何操作。)并且,郑重声明,
a &&= b;
不是有效的 Java。没有&&=
运算符。实际上,
a = a 和 a 之间几乎没有语义差异。 b;
和a = a && b;
。 (如果b
是变量或常量,则两个版本的结果将相同。当b
是具有 side 的子表达式时,仅存在语义差异-effects。在&
情况下,副作用总是发生,具体取决于a
的值。 code>。)在性能方面,需要在评估
b
的成本与测试和分支a
的值的成本之间进行权衡,以及避免对a
进行不必要的分配可能会节省成本。该分析并不直接,但除非计算 b 的成本不小,否则两个版本之间的性能差异太小,不值得考虑。From the Java Language Specification - 15.26.2 Compound Assignment Operators.
So
a &= b;
is equivalent toa = a & b;
.(In some usages, the type-casting makes a difference to the result, but in this one
b
has to beboolean
and the type-cast does nothing.)And, for the record,
a &&= b;
is not valid Java. There is no&&=
operator.In practice, there is little semantic difference between
a = a & b;
anda = a && b;
. (Ifb
is a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference whenb
is a subexpression that has side-effects. In the&
case, the side-effect always occurs. In the&&
case it occurs depending on the value ofa
.)On the performance side, the trade-off is between the cost of evaluating
b
, and the cost of a test and branch of the value ofa
, and the potential saving of avoiding an unnecessary assignment toa
. The analysis is not straight-forward, but unless the cost of calculatingb
is non-trivial, the performance difference between the two versions is too small to be worth considering.请参阅 JLS 的 15.22.2 。对于布尔操作数,
&
运算符是布尔值,而不是按位。对于布尔操作数,&&
和&
之间的唯一区别是,对于&&
它是短路的(意味着如果第一个操作数的计算结果为 false,则不会计算第二个操作数)。因此,在您的情况下,如果
b
是原语,则a = a && b,a = a & b
和a &= b
都做同样的事情。see 15.22.2 of the JLS. For boolean operands, the
&
operator is boolean, not bitwise. The only difference between&&
and&
for boolean operands is that for&&
it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).So in your case, if
b
is a primitive,a = a && b
,a = a & b
, anda &= b
all do the same thing.这是最后一张:
It's the last one:
下面是一个简单的测试方法:
输出是
b() was called
,因此计算右侧操作数。因此,正如其他人已经提到的,
a &= b
与a = a & 相同。 b.
。Here's a simple way to test it:
The output is
b() was called
, therefore the right-hand operand is evaluated.So, as already mentioned by others,
a &= b
is the same asa = a & b
.我使用布尔值遇到了类似的情况,如果 a 已经为 false,我想避免调用 b() 。
这对我有用:
i came across a similar situation using booleans where I wanted to avoid calling b() if a was already false.
This worked for me: