在Java中,将布尔值转换为int值的最常用方法是什么?


当前回答

如果true -> 1和false -> 0映射是你想要的,你可以这样做:

boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.

其他回答

int myInt = myBoolean ? 1 : 0;

^^

PS: true = 1, false = 0

如果true -> 1和false -> 0映射是你想要的,你可以这样做:

boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.

让我们使用boolean .compare(boolean, boolean)。函数的默认行为:如果两个值相等,则返回0,否则返回-1。

public int valueOf(Boolean flag) {
   return Boolean.compare(flag, Boolean.TRUE) + 1;
}

解释:我们知道Boolean.compare的默认返回值在不匹配的情况下是-1,所以+1使返回值为0为False, 1为True

public static int convBool(boolean b)
{
int convBool = 0;
if(b) convBool = 1;
return convBool;
}

然后使用:

convBool(aBool);

使用三元运算符是最简单、最有效、最易读的方法。我鼓励您使用这个解决方案。

然而,我忍不住要提出一种替代的、做作的、低效的、不可读的解决方案。

int boolToInt(Boolean b) {
    return b.compareTo(false);
}

嘿,人们喜欢投票给这么酷的答案!

Edit

顺便说一下,我经常看到从布尔型到int型的转换仅仅是为了比较两个值(通常是在compareTo方法的实现中)。布尔#compareTo是在这些特定情况下的方法。

编辑2

Java 7引入了一个新的实用函数,可以直接处理基本类型:Boolean#compare(感谢shmosel)

int boolToInt(boolean b) {
    return Boolean.compare(b, false);
}