在Java中,将布尔值转换为int值的最常用方法是什么?
当前回答
如果你想混淆,可以使用这个:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
其他回答
boolean b = ....;
int i = -("false".indexOf("" + b));
int val = b? 1 : 0;
import org.apache.commons.lang3.BooleanUtils;
boolean x = true;
int y= BooleanUtils.toInteger(x);
那要视情况而定。通常最简单的方法是最好的,因为它很容易理解:
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;
}
}
如果你想混淆,可以使用这个:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- 字符串不能识别为有效的日期时间“格式dd/MM/yyyy”
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?