在Java中,将布尔值转换为int值的最常用方法是什么?
当前回答
如果你想混淆,可以使用这个:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
其他回答
public static int convBool(boolean b)
{
int convBool = 0;
if(b) convBool = 1;
return convBool;
}
然后使用:
convBool(aBool);
boolean b = ....;
int i = -("false".indexOf("" + b));
int myInt = myBoolean ? 1 : 0;
^^
PS: true = 1, false = 0
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
推荐文章
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 如何舍入一个双到最近的Int在迅速?
- 将JSON字符串转换为HashMap
- web - inf在Java EE web应用程序中用于什么?
- Java 8: Lambda-Streams,过滤方法与异常
- 将JsonNode转换为POJO