Java &= 运算符是否适用 &或&&? [英] Does the Java &= operator apply & or &&?

查看:68
本文介绍了Java &= 运算符是否适用 &或&&?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设

boolean a = false;

我想知道是否要这样做:

I was wondering if doing:

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.

推荐答案

来自 Java 语言规范 - 15.26.2 复合赋值运算符.

From the Java Language Specification - 15.26.2 Compound Assignment Operators.

E1 op= E2 形式的复合赋值表达式等价于 E1 = (T)((E1) op (E2)),其中TE1 的类型,除了 E1 只计算一次.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

所以 a &= b; 等价于 a = a &b;.

(在某些用法中,类型转换会对结果产生影响,但在这种情况下,b 必须是 boolean 并且类型转换什么都不做.)

(In some usages, the type-casting makes a difference to the result, but in this one b has to be boolean and the type-cast does nothing.)

而且,根据记录,a &&= b; 不是有效的 Java.没有 &&= 运算符.

And, for the record, a &&= b; is not valid Java. There is no &&= operator.

在实践中,a = a & 之间几乎没有语义差异.b;a = a &&b;.(如果 b 是变量或常量,则两个版本的结果将相同.当 b 是具有边的子表达式时,只有语义差异-effects.在&的情况下,副作用总是发生.在&&的情况下,它的发生取决于a.)

In practice, there is little semantic difference between a = a & b; and a = a && b;. (If b is a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference when b is a subexpression that has side-effects. In the & case, the side-effect always occurs. In the && case it occurs depending on the value of a.)

在性能方面,权衡是在评估 b 的成本与 a 的值的测试和分支的成本之间,以及避免对 a 进行不必要的分配的潜在节省.分析不是直截了当的,但除非计算b的代价不小,否则两个版本之间的性能差异太小,不值得考虑.

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 of a, and the potential saving of avoiding an unnecessary assignment to a. The analysis is not straight-forward, but unless the cost of calculating b is non-trivial, the performance difference between the two versions is too small to be worth considering.

这篇关于Java &= 运算符是否适用 &或&&?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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