Jon*_*INE 549
int myInt = myBoolean ? 1 : 0;
Run Code Online (Sandbox Code Playgroud)
^^
PS:true = 1,false = 0
Gro*_*uez 149
int val = b? 1 : 0;
Run Code Online (Sandbox Code Playgroud)
bar*_*jak 55
使用三元运算符是实现您想要的最简单,最有效和最可读的方式.我鼓励你使用这个解决方案.
但是,我无法抗拒提出一种替代的,人为的,低效的,不可读的解决方案.
int boolToInt(Boolean b) {
return b.compareTo(false);
}
Run Code Online (Sandbox Code Playgroud)
嘿,人们喜欢投票给这么酷的答案!
编辑
顺便说一句,我经常看到从布尔到int的转换,其唯一目的是对两个值进行比较(通常,在compareTo
方法的实现中).Boolean#compareTo
是这些特定情况下的方法.
编辑2
Java 7引入了一个新的实用程序函数,它可以直接使用原始类型,Boolean#compare
(谢谢shmosel)
int boolToInt(boolean b) {
return Boolean.compare(b, false);
}
Run Code Online (Sandbox Code Playgroud)
Tho*_*sen 46
boolean b = ....;
int i = -("false".indexOf("" + b));
Run Code Online (Sandbox Code Playgroud)
小智 26
public int boolToInt(boolean b) {
return b ? 1 : 0;
}
Run Code Online (Sandbox Code Playgroud)
简单
小智 20
import org.apache.commons.lang3.BooleanUtils;
boolean x = true;
int y= BooleanUtils.toInteger(x);
Run Code Online (Sandbox Code Playgroud)
Hen*_*ann 12
这取决于具体情况.通常最简单的方法是最好的,因为它很容易理解:
if (something) {
otherThing = 1;
} else {
otherThing = 0;
}
Run Code Online (Sandbox Code Playgroud)
要么
int otherThing = something ? 1 : 0;
Run Code Online (Sandbox Code Playgroud)
但有时使用Enum而不是布尔标志会很有用.假设存在同步和异步过程:
Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());
Run Code Online (Sandbox Code Playgroud)
在Java中,枚举可以有其他属性和方法:
public enum Process {
SYNCHRONOUS (0),
ASYNCHRONOUS (1);
private int code;
private Process (int code) {
this.code = code;
}
public int getCode() {
return code;
}
}
Run Code Online (Sandbox Code Playgroud)
如果您使用Apache Commons Lang(我认为很多项目都使用它),您可以像这样使用它:
int myInt = BooleanUtils.toInteger(boolean_expression);
Run Code Online (Sandbox Code Playgroud)
toInteger
如果boolean_expression
为true,则返回1 ,否则返回0
如果true -> 1
和false -> 0
映射是你想要的,你可以这样做:
boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.
Run Code Online (Sandbox Code Playgroud)
让我们玩把戏Boolean.compare(boolean, boolean)
。函数的默认行为:如果两个值相等则返回0
否则返回-1
。
public int valueOf(Boolean flag) {
return Boolean.compare(flag, Boolean.TRUE) + 1;
}
Run Code Online (Sandbox Code Playgroud)
说明:正如我们所知,在不匹配的情况下,Boolean.compare 的默认返回值为 -1,因此 +1 使返回值为0 forFalse
和1 forTrue
如果要混淆,请使用:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
Run Code Online (Sandbox Code Playgroud)