2. 数据类型

在Java中,整数可以用int基本数据类型或Integer包装类表示。int是32位有符号整数,采用二进制补码编码;而Integer包装类支持无符号运算,并将原始值转为对象以用于泛型

至于boolean类型:

  • 内存大小不固定,取决于操作系统和JVM实现
  • 对应的Boolean包装类使其具备对象特性

核心转换规则:将true视为1、false视为0,我们就能通过多种方式实现类型转换。

3. 基本类型boolean转int

通过条件判断实现转换:

public int booleanPrimitiveToInt(boolean foo) {
    int bar = 0;
    if (foo) {
        bar = 1;
    }
    return bar;
}

更简洁的三元运算符写法:

public int booleanPrimitiveToIntTernary(boolean foo) {
    return (foo) ? 1 : 0;
}

这种纯基本数据类型操作,直接返回1(true)或0(false),简单粗暴但有效。

4. 包装类方案

利用Boolean包装类有两种转换方式:

  • 使用静态方法
  • 调用对象方法

4.1 静态方法

Boolean.compare()是个实用工具:

public static int booleanObjectToInt(boolean foo) {
    return Boolean.compare(foo, false);
}

关键原理

  • foofalse时,比较结果为0
  • footrue时,返回1(因为true大于false

反向操作也成立:

public static int booleanObjectToIntInverse(boolean foo) { 
    return Boolean.compare(foo, true) + 1;
}

4.2 Boolean对象方法

直接调用对象方法:

public static int booleanObjectMethodToInt(Boolean foo) {
    return foo.compareTo(false);
}

效果与静态方法相同,同样支持反向操作(修改参数为true并结果加1)。

5. Apache Commons方案

Apache Commons Lang3库提供了BooleanUtils工具类。先添加Maven依赖:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>
</dependency>

使用toInteger()方法:

public static int booleanUtilsToInt(Boolean foo) {
    return BooleanUtils.toInteger(foo);
}

内部实现仍是三元运算,但代码更简洁,适合项目统一风格。

6. int转boolean

转换规则需要明确定义:

  • true → 整数值为1
  • false → 整数值为0
  • 其他值 → 抛出异常

6.1 使用条件语句

基础实现:

boolean intToBooleanWithThrowing(int theInt) {
    if (theInt == 1) {
        return true;
    }
    if (theInt == 0) {
        return false;
    }
    throw new IllegalArgumentException("Only 0 or 1 is allowed.");
}

6.2 BooleanUtils.toBoolean()

Apache Commons提供更灵活的转换方法:

public static boolean toBoolean(final int value, final int trueValue, final int falseValue) {
    if (value == trueValue) {
        return true;
    } else if (value == falseValue) {
        return false;
    } else {
        throw new IllegalArgumentException("The Integer did not match either specified value");
    }
}

使用示例:

int trueValue = 1;
int falseValue = 0;
 
assertTrue(BooleanUtils.toBoolean(1, trueValue, falseValue));
assertFalse(BooleanUtils.toBoolean(0, trueValue, falseValue));
assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean(42, trueValue, falseValue));
assertThrows(IllegalArgumentException.class, () -> BooleanUtils.toBoolean(-42, trueValue, falseValue));

6.3 其他转换规则

常见场景需要自定义规则:

// 正数转true,否则false
boolean intToBoolean(int theInt) {
    return theInt > 0;
}

Apache Commons也提供简化方法:

public static boolean toBoolean(final int value) {
    return value != 0;
}

核心逻辑

  • 0 → false
  • 非0 → true

7. 总结

本文系统梳理了Java中booleanint的转换方案:

  • 基础转换:三元运算符最直接
  • 包装类方案:适合对象化操作场景
  • 工具库方案:Apache Commons提供标准化实现
  • 反向转换:需明确定义规则,避免踩坑

根据具体场景选择方案,保持代码清晰可维护是关键。


原始标题:Convert Between boolean and int in Java | Baeldung