在Java中,将布尔值转换为int值的最常用方法是什么?
当前回答
public static int convBool(boolean b)
{
int convBool = 0;
if(b) convBool = 1;
return convBool;
}
然后使用:
convBool(aBool);
其他回答
如果你想混淆,可以使用这个:
System.out.println( 1 & Boolean.hashCode( true ) >> 1 ); // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0
int val = b? 1 : 0;
那要视情况而定。通常最简单的方法是最好的,因为它很容易理解:
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;
}
}
public int boolToInt(boolean b) {
return b ? 1 : 0;
}
简单的
int myInt = myBoolean ? 1 : 0;
^^
PS: true = 1, false = 0
推荐文章
- c#和Java中的泛型有什么不同?和模板在c++ ?
- 在Java中,流相对于循环的优势是什么?
- Jersey在未找到InjectionManagerFactory时停止工作
- 在Java流是peek真的只是调试?
- Recyclerview不调用onCreateViewHolder
- 如何舍入一个双到最近的Int在迅速?
- 将JSON字符串转换为HashMap
- web - inf在Java EE web应用程序中用于什么?
- Java 8: Lambda-Streams,过滤方法与异常
- 将JsonNode转换为POJO
- 如何查看IntelliJ中的编译错误列表?
- Java SimpleDateFormat("yyyy-MM-dd' t ' hh:mm:ss' z '")给出的时区为IST
- 杰克逊克服下划线,支持骆驼案
- List、List<?>, List<T>, List<E>, List<Object>
- 在Java中转换字符串到日历对象