在Java中将boolean转换为int

在Java中将boolean转换为int最常用的方法是什么?

 int myInt = (myBoolean) ? 1 : 0; 

^^

PS:true = 1和false = 0

 int val = b? 1 : 0; 

使用三元运算符是最简单,最有效,最可读的方法来做你想要的。 我鼓励你使用这个解决scheme。

但是,我忍不住要提出一种替代性的,人为的,低效的,不可读的解决scheme。

 int boolToInt(Boolean b) { return b.compareTo(false); } 

嘿,人们喜欢投票这样很酷的答案!

编辑

顺便说一下,我经常看到从布尔型到整型的转换,仅用于比较两个值(通常在compareTo方法的实现中)。 在这些特定的情况下, Boolean#compareTo是要走的路。

编辑2

Java 7引入了一个新的效用函数,它直接与原始types一起工作, Boolean#compare (Thanks shmosel

 int boolToInt(boolean b) { return Boolean.compare(b, false); } 
 boolean b = ....; int i = -("false".indexOf("" + b)); 
 public int boolToInt(boolean b) { return b ? 1 : 0; } 

简单

这取决于情况。 通常最简单的方法是最好的,因为它很容易理解:

 if (something) { otherThing = 1; } else { otherThing = 0; } 

要么

 int otherThing = something ? 1 : 0; 

但有时使用枚举而不是布尔标志是有用的。 假设有同步和asynchronous进程:

 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; } } 

如果true -> 1false -> 0映射是你想要的,你可以这样做:

 boolean b = true; int i = b ? 1 : 0; // assigns 1 to i. 
 import org.apache.commons.lang3.BooleanUtils; boolean x = true; int y= BooleanUtils.toInteger(x); 

如果你想混淆,使用这个:

 System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1 System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0 

让我们玩Boolean.compare(boolean, boolean)技巧。 函数的默认行为:如果两个值相等,则返回0否则返回-1

 public int valueOf(Boolean flag) { return Boolean.compare(flag, Boolean.TRUE) + 1; } 

说明 :正如我们所知的,在失配的情况下,Boolean.compare的默认返回值为-1,所以+1将返回值设为False ,返回值为True

如果你使用Apache Commons Lang (我认为很多项目使用它),你可以像这样使用它:

 int myInt = BooleanUtils.toInteger(boolean_expression); 

如果boolean_expression为true, toInteger方法返回1,否则返回0