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


当前回答

boolean b = ....; 
int i = -("false".indexOf("" + b));

其他回答

如果你想混淆,可以使用这个:

System.out.println( 1 & Boolean.hashCode( true ) >> 1 );  // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
int myInt = myBoolean ? 1 : 0;

^^

PS: true = 1, false = 0

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

int myInt = BooleanUtils.toInteger(boolean_expression); 

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

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

boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.
import org.apache.commons.lang3.BooleanUtils;
boolean x = true;   
int y= BooleanUtils.toInteger(x);