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

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.

其他回答

它是这个的缩写:

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

|是位或。

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

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

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

or

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

我正在寻找关于|=在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.DEFAULT_SOUND;

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

其中|是按位的OR运算符。

这里引用了所有的运算符。

之所以使用逐位操作符,是因为通常情况下,这些常量使整型对象可以带位。

如果你观察这些常数,你会发现它们是2的幂:

public static final int DEFAULT_SOUND = 1;
public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary
public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary

因此,您可以使用位或来添加标志

int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011

so

myFlags |= DEFAULT_LIGHTS;

简单地说就是我们添加了一个标志。

对称地,我们使用&来测试标志的设置:

boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;