Java 中用竖线分隔的多个值

Multiple values separated by a pipe in Java

我与 Java 一起进行 Android 开发已有一段时间了。但是,直到今天我才注意到可以这样做:

int myInt = 1|3|4;

据我所知,变量 myInt 应该只有一个整数值。有人能解释一下这是怎么回事吗?

谢谢!

Java 中的 | 字符是按位或(如评论中所述)。这通常用于组合标志,如您给出的示例所示。

在这种情况下,各个值是 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

然后在selectedOptions变量中设置FEATURE_1FEATURE_2

然后要稍后使用 selectedOptions 变量,应用程序将使用按位与运算 & 并且会有如下代码:

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
}

这是一种常见的编码模式。