最近我看到一个使用这个的代码:
boolean val = something();
val |= somethingElse();
有趣的部分是在 boolean 原始类型上创建的 |=(类似二进制)运算符。
令我惊讶的是, boolean 值存在 |=,就好像它是整数类型一样,并在 Java 规范中搜索该运算符,但找不到。
如果左值已经为真,我会很好奇是否计算右操作数。
有人可以指出我的 Java 规范吗?
最佳答案
来自 JLS:
15.26.2. Compound Assignment Operators
A compound assignment expression of the form
E1 op= E2
is equivalent toE1 = (T) ((E1) op (E2))
, whereT
is the type ofE1
, except thatE1
is evaluated only once.15.22.2. Boolean Logical Operators
&
,^
, and|
When both operands of a
&
,^
, or|
operator are of typeboolean
orBoolean
, then the type of the bitwise operator expression isboolean
. In all cases, the operands are subject to unboxing conversion (§5.1.8) as necessary.For
|
, the result value is false if both operand values are false; otherwise, the result is true.
这意味着
val |= somethingElse();
严格等价于
val = val | somethingElse();
(假设 somethingElse()
返回 boolean
或 Boolean
)。
I'd be curious if right operand is evaluated if left value already is true.
是的,它会被评估,因为 |
不会短路:
15.7.2. Evaluate Operands before Operation
The Java programming language guarantees that every operand of an operator (except the conditional operators
&&
,||
, and? :
) appears to be fully evaluated before any part of the operation itself is performed.15.24. Conditional-Or Operator
||
Thus,
||
computes the same result as|
onboolean
orBoolean
operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.
关于Java boolean 值 |= 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15411219/