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


当前回答

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

其他回答

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

^^

PS: true = 1, false = 0

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

然后使用:

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

简单的

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

System.out.println( 1 & Boolean.hashCode( true ) >> 1 );  // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0