在Java中,将boolean
类型转换为int
类型的最常用方式是什么?
在Java中,将boolean
类型转换为int
类型的最常用方式是什么?
int myInt = myBoolean ? 1 : 0;
PS: true = 1,false = 0。
(foo && (!bar || baz)) ? 1 : 0
中的那样。显然,如果它只是一个标识符,那么括号是不必要且不可取的。 - Blrfl(boolean expression) ? 1 : 0;
更容易理解。我认为 my
前缀让它看起来像一个变量。 - dixhomfoo && (!bar || baz) ? 1 : 0
将会是一个语法错误。(我知道已经过去6年了) - Konrad Morawskiint val = b? 1 : 0;
使用三元运算符是实现你想要的任务最简单、最高效、最可读的方式。我鼓励你使用这种解决方案。
然而,我不禁提出一个替代的、牵强附会的、低效难懂的方案。
int boolToInt(Boolean b) {
return b.compareTo(false);
}
嘿,人们喜欢为这样的很棒的答案投票!
编辑
顺便提一下,我经常看到将布尔值转换为整数的转换,目的只是为了比较这两个值(通常在compareTo
方法的实现中)。在这些特定情况下,Boolean#compareTo
是正确的选择。
编辑2
Java 7引入了一个新的实用函数,直接使用原始类型,即Boolean#compare
(感谢shmosel)。
int boolToInt(boolean b) {
return Boolean.compare(b, false);
}
Boolean.compare()
来避免自动装箱。Boolean.compareTo()
的文档没有说明它将返回1,只有在“该对象表示true且参数表示false时返回正值”。boolean b = ....;
int i = -("false".indexOf("" + b));
import org.apache.commons.lang3.BooleanUtils;
boolean x = true;
int y= BooleanUtils.toInteger(x);
BooleanUtils.toInteger
实现的代码只是 return bool ? 1 : 0;
。 - Solomon Uckoxyz.stream().map(BooleanUtils::toInteger)
比 xyz.stream().map(x -> x ? 1 : 0)
更易读。 - bb1950328public int boolToInt(boolean b) {
return b ? 1 : 0;
}
简单的
如果您使用 Apache Commons Lang (我认为很多项目都在使用它),您可以像这样使用:
int myInt = BooleanUtils.toInteger(boolean_expression);
toInteger
方法如果 boolean_expression
为真返回1,否则返回0。
BooleanUtils.toInteger
的实现只是简单地返回 bool ? 1 : 0;
。 - Solomon Ucko那要看情况而定。通常最简单的方法是最好的,因为它易于理解:
if (something) {
otherThing = 1;
} else {
otherThing = 0;
}
或者int otherThing = something ? 1 : 0;
但有时使用枚举而不是布尔标志更为实用。假设存在同步和异步过程:
Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());
在Java中,枚举可以具有额外的属性和方法:public enum Process {
SYNCHRONOUS (0),
ASYNCHRONOUS (1);
private int code;
private Process (int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
?:
的另一个原因是,您可以在if块中设置断点。 - Thorbjørn Ravn Andersentrue -> 1
和false -> 0
进行映射,可以按照以下步骤操作:boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0