Java:将原始布尔值转换为原始int(0,1)的好方法

时间:2014-08-26 19:29:18

标签: java type-conversion

我知道它应该很简单但是......

  • 我有原始 java boolean。
  • 我认为这样简单的事情不需要额外的方法编码。
  • 我非常不喜欢三元运算符和内联条件(?,对于那些想要声誉并试图回答任何问题的人来说,即使没有阅读问题也是如此)。所以(value ? 1 : 0)不适合我。
  • 我不能使用像value.compareTo(false)这样的好片段,因为它是primitive

我想得到的是最后一点,但对于原语。 很惊讶没有好办法做这么简单有用的转换?我也是。你的谷歌比我的大吗? ;-D

更新

好的,最后我决定为这种情况编写自己的方法,因为不仅有类型转换,而且还有一些可以在将来扩展的逻辑,我想把它封装起来。感谢所有参与的人。

6 个答案:

答案 0 :(得分:2)

如果你不能严格使用value.compareTo(false),因为它是原始的,那么

怎么样
Boolean.valueOf(value).compareTo(Boolean.FALSE);

答案 1 :(得分:1)

这个怎么样?

boolean x = true;

System.out.println(Boolean.compare(x, false));

路号 2

System.out.println(5 - Boolean.toString(x).length());

路数 3 (更长):

boolean x = true;

try{
    System.out.println(Boolean.toString(x).charAt(4) - 101);
}catch(StringIndexOutOfBoundsException e){
    System.out.println(1);
}

答案 2 :(得分:0)

没有好办法。额外的函数定义并不坏。如果你讨厌三元,只需定义一个函数:

int bool_to_int(boolean mybool) {
    if (mybool)
        return 1;
    return 0;
}

答案 3 :(得分:0)

使用三元运算符是最简单,最有效,最易读的方法,可以满足您的需求。我鼓励你使用这个解决方案。

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

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

答案 4 :(得分:0)

好的,最后这是我发现的最好的事情:

public class Main {

    public static int resultCode(final boolean flag) {
        return Boolean.compare(flag, false);
    }

    public static void main(final String[] args) {
        boolean v1 = false;
        boolean v2 = true;
        System.out.println(v1 + " > " + resultCode(v1));
        System.out.println(v2 + " > " + resultCode(v2));
    }
}

答案 5 :(得分:0)

以下是您的方法的一些想法 - 这些都令人兴奋,因为它比b ? 1: 0复杂得多。

int bi1(boolean b) {
    // The number of items in a set containing both false and the value
    Set<Boolean> s = new HashSet<Boolean>();
    s.add(b);
    s.add(false);
    return s.size() - 1;
}

int bi2(boolean b) {
    // Side-effect usage.
    int bi = 0;
    boolean x = (b && (bi = 1) == 0);
    return bi;
}

int bi3(boolean b) {
    // Using Compareto in a gratuitously obscure way.
    return (int) Math.signum(("" + b).compareTo(Boolean.FALSE.toString()));
}

int bi4(boolean b) {
    // A twiddle too far.
    return ((int) ("" + !b).charAt(0)) >> 1 & 1;
}

int bi5(boolean b) {
    // The old if heave
    if (b) {
        return 1;
    } else {
        return 0;
    }
}

static final List<Boolean> ltf = Arrays.asList(false, true);

int bi6(boolean b) {
    // List twiddling.
    return ltf.indexOf(b);
}

你还想要多少?

相关问题