在Java中,将布尔值转换为int值的最常用方法是什么?


当前回答

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

System.out.println( 1 & Boolean.hashCode( true ) >> 1 );  // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 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;
    }
}

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

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

解释:我们知道Boolean.compare的默认返回值在不匹配的情况下是-1,所以+1使返回值为0为False, 1为True

public static int convBool(boolean b)
{
int convBool = 0;
if(b) convBool = 1;
return convBool;
}

然后使用:

convBool(aBool);
public int boolToInt(boolean b) {
    return b ? 1 : 0;
}

简单的

int myInt = myBoolean ? 1 : 0;

^^

PS: true = 1, false = 0