我尝试使用谷歌搜索和堆栈溢出搜索,但没有显示任何结果。我在开源库代码中看到过:

Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;

“|=”(管道相等运算符)是什么意思?


当前回答

备注:||=不存在。(逻辑或) 你可以使用

y= y || expr; // expr is NOT evaluated if y==true

or

y = expr ? true : y;  // expr is always evaluated.

其他回答

|是位或操作符,它像+=一样被应用。

备注:||=不存在。(逻辑或) 你可以使用

y= y || expr; // expr is NOT evaluated if y==true

or

y = expr ? true : y;  // expr is always evaluated.

你的问题已经有了充分的答案。但我的回答可能会帮助你更多地了解|=一类二进制运算符。

我正在为位操作符写表: 以下是有效的:

----------------------------------------------------------------------------------------
Operator   Description                                   Example
----------------------------------------------------------------------------------------
|=        bitwise inclusive OR and assignment operator   C |= 2 is same as C = C | 2
^=        bitwise exclusive OR and assignment operator   C ^= 2 is same as C = C ^ 2
&=        Bitwise AND assignment operator                C &= 2 is same as C = C & 2
<<=       Left shift AND assignment operator             C <<= 2 is same as C = C << 2
>>=       Right shift AND assignment operator            C >>= 2 is same as C = C >> 2  
----------------------------------------------------------------------------------------

注意所有操作符都是二进制操作符。

另外注意:(对于以下几点,我想补充我的答案)

>>>是Java中的位运算符,称为Unsigned shift 但是>>>=不是Java中的运算符。> > > =操作符 ~是按位的补位,0到1和1到0(一元运算符),但~=不是运算符。 此外,!调用逻辑NOT运算符,但是!=检查两个操作数的值是否相等,如果值不相等则condition为true。(A != B)是正确的。其中A=!B表示如果B为真,则A为假(如果B为假,则A为真)。

边注:|不叫管道,而是叫OR,管道是shell术语,将一个进程转移到下一个进程。

我正在寻找关于|=在Groovy中做什么的答案,虽然上面的答案是正确的,但它们并没有帮助我理解我正在看的一段特定的代码。

特别地,当应用于一个布尔变量"|="时,当它第一次在右边遇到一个真表达式时,它将把它设置为TRUE,并在所有|=后续调用中保持它的TRUE值。像门闩一样。

这里有一个简单的例子:

groovy> boolean result  
groovy> //------------ 
groovy> println result           //<-- False by default
groovy> println result |= false 
groovy> println result |= true   //<-- set to True and latched on to it
groovy> println result |= false 

输出:

false
false
true
true

编辑: 为什么这个有用?

考虑这样一种情况,您想知道在各种对象上是否发生了任何更改,如果发生了更改,则通知其中一个更改。所以,你会设置一个hasChanges布尔值,并将其设置为|= diff (a,b),然后|= dif(b,c)等。 下面是一个简单的例子:

groovy> boolean hasChanges, a, b, c, d 
groovy> diff = {x,y -> x!=y}  
groovy> hasChanges |= diff(a,b) 
groovy> hasChanges |= diff(b,c) 
groovy> hasChanges |= diff(true,false) 
groovy> hasChanges |= diff(c,d) 
groovy> hasChanges 

Result: true

它是这个的缩写:

notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;

|是位或。