我一直在使用Java进行Android开发.但是,直到今天我才注意到可以这样做:
int myInt = 1|3|4;
Run Code Online (Sandbox Code Playgroud)
据我所知,变量myInt应该只有一个整数值.有人能解释一下这里发生了什么吗?
谢谢!
|Java中的字符是按位OR(如注释中所述).这通常用于组合标志,如您给出的示例中所示.
在这种情况下,单个值是2的幂,这意味着该值只有一位1.
例如,给定代码如下:
static final int FEATURE_1 = 1; // Binary 00000001
static final int FEATURE_2 = 2; // Binary 00000010
static final int FEATURE_3 = 4; // Binary 00000100
static final int FEATURE_4 = 8; // Binary 00001000
int selectedOptions = FEATURE_1 | FEATURE_3; // Binary 00000101
Run Code Online (Sandbox Code Playgroud)
然后FEATURE_1和FEATURE_2在被设置selectedOptions的变量.
然后,为了selectedOptions稍后使用该变量,应用程序将使用按位AND运算,&并且会有如下代码:
if ((selectedOptions & FEATURE_1) == FEATURE_1) {
// Implement feature 1
}
if ((selectedOptions & FEATURE_2) == FEATURE_2) {
// Implement feature 2
}
if ((selectedOptions & FEATURE_3) == FEATURE_3) {
// Implement feature 3
}
if ((selectedOptions & FEATURE_4) == FEATURE_4) {
// Implement feature 4
}
Run Code Online (Sandbox Code Playgroud)
这是一种常见的编码模式.