在Java中,将布尔值转换为int值的最常用方法是什么?
当前回答
让我们使用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
其他回答
如果你想混淆,可以使用这个:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
int val = b? 1 : 0;
如果true -> 1和false -> 0映射是你想要的,你可以这样做:
boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.
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;
}
简单的
推荐文章
- 泛型类中的静态方法?
- 如何在JPA中持久化类型列表<字符串>的属性?
- 考虑在配置中定义一个'package'类型的bean [Spring-Boot]
- Java注释中的/**和/*
- java8 LocalDate Jackson格式
- Android Studio谷歌JAR文件导致GC开销限制超过错误
- 如何在Intellij生成串行版本UID
- NumPy或Pandas:保持数组类型为整数,同时具有NaN值
- “比较法违反其总合同!”
- 从Java项目生成UML类图
- 正确地从一个<Integer>的列表中移除一个整数
- Java开关语句:需要常量表达式,但它是常量
- Java的assertEquals方法可靠吗?
- 如何在Java中获得系统变量值?
- 比较Java中2个XML文档的最佳方法