在Java中,将布尔值转换为int值的最常用方法是什么?
当前回答
如果true -> 1和false -> 0映射是你想要的,你可以这样做:
boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.
其他回答
如果你使用Apache Commons Lang(我认为很多项目都在使用它),你可以这样使用它:
int myInt = BooleanUtils.toInteger(boolean_expression);
toInteger方法如果boolean_expression为真则返回1,否则返回0
boolean b = ....;
int i = -("false".indexOf("" + b));
int myInt = myBoolean ? 1 : 0;
^^
PS: true = 1, false = 0
那要视情况而定。通常最简单的方法是最好的,因为它很容易理解:
if (something) {
otherThing = 1;
} else {
otherThing = 0;
}
or
int otherThing = something ? 1 : 0;
但有时使用Enum而不是布尔标志是有用的。让我们假设有同步和异步进程:
Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());
在Java中,enum可以有额外的属性和方法:
public enum Process {
SYNCHRONOUS (0),
ASYNCHRONOUS (1);
private int code;
private Process (int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
使用三元运算符是最简单、最有效、最易读的方法。我鼓励您使用这个解决方案。
然而,我忍不住要提出一种替代的、做作的、低效的、不可读的解决方案。
int boolToInt(Boolean b) {
return b.compareTo(false);
}
嘿,人们喜欢投票给这么酷的答案!
Edit
顺便说一下,我经常看到从布尔型到int型的转换仅仅是为了比较两个值(通常是在compareTo方法的实现中)。布尔#compareTo是在这些特定情况下的方法。
编辑2
Java 7引入了一个新的实用函数,可以直接处理基本类型:Boolean#compare(感谢shmosel)
int boolToInt(boolean b) {
return Boolean.compare(b, false);
}
推荐文章
- 在流中使用Java 8 foreach循环移动到下一项
- 访问限制:'Application'类型不是API(必需库rt.jar的限制)
- 用Java计算两个日期之间的天数
- 如何配置slf4j-simple
- 在Jar文件中运行类
- 带参数的可运行?
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 我可以在Java中设置enum起始值吗?
- Java中的回调函数
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 如何舍入一个双到最近的Int在迅速?