我想知道是否有一种方法可以在不使用if语句的情况下将布尔值转换为int (因为不会中断管道)。例如,我可以这样写
int boolToInt( boolean b ){
if ( b )
return 1
return 0
但是我想知道是否有一种方法可以不使用if语句,就像Python一样
bool = True
num = 1 * ( bool )
我也觉得你可以
boolean bool = True;
int myint = Boolean.valueOf( bool ).compareTo( false );
然而,这会创建一个额外的对象,所以它真的很浪费,我发现它甚至比if语句的方式还要慢(这不一定是低效的,只是有一个缺点)。
发布于 2013-06-01 09:54:34
除非在if中,否则不能使用布尔值。但是,这并不意味着在程序集级别上会有一个分支。
如果您检查该方法的编译代码(顺便说一句,使用return b ? 1 : 0;
编译成完全相同的指令),您将看到它没有使用跳转:
0x0000000002672580: sub $0x18,%rsp
0x0000000002672587: mov %rbp,0x10(%rsp) ;*synchronization entry
0x000000000267258c: mov %edx,%eax
0x000000000267258e: add $0x10,%rsp
0x0000000002672592: pop %rbp
0x0000000002672593: test %eax,-0x2542599(%rip) # 0x0000000000130000
; {poll_return}
0x00000000025b2599: retq
注意:这是在hotspot服务器7上-你可能会在不同的虚拟机上得到不同的结果。
发布于 2013-06-01 09:34:50
使用?:运算符:( b ? 1 : 0 )
发布于 2015-07-09 19:32:37
否则,您可以使用Apache Commons BooleanUtils.toInteger方法,它的工作方式非常出色……
// Converts a boolean to an int specifying the conversion values.
static int toInteger(boolean bool, int trueValue, int falseValue)
// Converts a Boolean to an int specifying the conversion values.
static int toInteger(Boolean bool, int trueValue, int falseValue, int nullValue)
https://stackoverflow.com/questions/16868196
复制相似问题