“=”是什么意思?(管道等号操作符)

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (36)

我试着用Google搜索和Stack溢出搜索,但没有显示任何结果。我在开源库代码中看到过这样的情况:

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

“=”是什么?pipe equal operator)刻薄?

提问于
用户回答回答于

|=读起来和+=.

notification.defaults |= Notification.DEFAULT_SOUND;

是相同的

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

|是位或运算符。

之所以使用按位计算的运算符,是因为这些常量使int能够携带标志。

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

所以

myFlags |= DEFAULT_LIGHTS;

简单地说就是我们添加了一个旗子。

对称地,我们测试一个标志被设置为&

boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;
用户回答回答于

以下是有效的办法:

----------------------------------------------------------------------------------------
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  
----------------------------------------------------------------------------------------

注意,所有运算符都是二进制运算符。

扫码关注云+社区