Convert boolean to int in Java

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


int myInt = myBoolean ? 1 : 0;

^^

PS : true = 1 and false = 0


int val = b? 1 : 0;

Using the ternary operator is the most simple, most efficient, and most readable way to do what you want. I encourage you to use this solution.

However, I can't resist to propose an alternative, contrived, inefficient, unreadable solution.

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

Hey, people like to vote for such cool answers !

Edit

By the way, I often saw conversions from a boolean to an int for the sole purpose of doing a comparison of the two values (generally, in implementations of compareTo method). Boolean#compareTo is the way to go in those specific cases.

Edit 2

Java 7 introduced a new utility function that works with primitive types directly, Boolean#compare (Thanks shmosel)

int boolToInt(boolean b) {
    return Boolean.compare(b, false);
}
链接地址: http://www.djcxy.com/p/40240.html

上一篇: 所有可能的数组初始化语法

下一篇: 在Java中将boolean转换为int