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


当前回答

public int boolToInt(boolean b) {
    return b ? 1 : 0;
}

简单的

其他回答

int val = b? 1 : 0;
boolean b = ....; 
int i = -("false".indexOf("" + b));

让我们使用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

import org.apache.commons.lang3.BooleanUtils;
boolean x = true;   
int y= BooleanUtils.toInteger(x);

如果你使用Apache Commons Lang(我认为很多项目都在使用它),你可以这样使用它:

int myInt = BooleanUtils.toInteger(boolean_expression); 

toInteger方法如果boolean_expression为真则返回1,否则返回0