繁体   English   中英

在Java中将布尔值转换为int

[英]Convert boolean to int in Java

在 Java 中将boolean转换为int的最被接受的方法是什么?

int myInt = myBoolean ? 1 : 0;

^^

PS:真=1,假=0

int val = b? 1 : 0;

使用三元运算符是做您想做的事情的最简单、最有效和最易读的方法。 我鼓励您使用此解决方案。

但是,我无法抗拒提出一个替代的、人为的、低效的、不可读的解决方案。

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

嘿,人们喜欢投票给这么酷的答案!

编辑

顺便说一句,我经常看到从布尔值到 int 的转换,其唯一目的是比较两个值(通常,在compareTo方法的实现中)。 Boolean#compareTo是这些特定情况下的方法。

编辑 2

Java 7 引入了一个新的实用函数,可以直接处理原始类型, Boolean#compare (感谢shmosel

int boolToInt(boolean b) {
    return Boolean.compare(b, false);
}
boolean b = ....; 
int i = -("false".indexOf("" + b));
public int boolToInt(boolean b) {
    return b ? 1 : 0;
}

简单的

import org.apache.commons.lang3.BooleanUtils;
boolean x = true;   
int y= BooleanUtils.toInteger(x);

如果您使用Apache Commons Lang (我认为很多项目都使用它),您可以像这样使用它:

int myInt = BooleanUtils.toInteger(boolean_expression); 

如果boolean_expression为真, toInteger方法返回 1,否则返回 0

那要看情况了。 通常最简单的方法是最好的,因为它很容易理解:

if (something) {
    otherThing = 1;
} else {
    otherThing = 0;
}

或者

int otherThing = something ? 1 : 0;

但有时使用 Enum 而不是布尔标志很有用。 假设有同步和异步进程:

Process process = Process.SYNCHRONOUS;
System.out.println(process.getCode());

在 Java 中,枚举可以有额外的属性和方法:

public enum Process {

    SYNCHRONOUS (0),
    ASYNCHRONOUS (1);

    private int code;
    private Process (int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }
}

如果true -> 1false -> 0映射是你想要的,你可以这样做:

boolean b = true;
int i = b ? 1 : 0; // assigns 1 to i.

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

System.out.println( 1 & Boolean.hashCode( true ) >> 1 );  // 1
System.out.println( 1 & Boolean.hashCode( false ) >> 1 ); // 0

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

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

说明:正如我们所知,在不匹配的情况下,Boolean.compare 的默认返回值为 -1,因此 +1 使返回值为0False ,为1True

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

然后使用:

convBool(aBool);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM