一段时间以来,我一直在使用 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
然后 FEATURE_1
和 FEATURE_2
在 selectedOptions
变量中设置。
然后为了稍后使用 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
}
这是一种常见的编码模式。
关于java - Java中用管道分隔的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31288234/