Converting Boolean to Integer in Java without If-Statements

后端 未结 12 1891
盖世英雄少女心
盖世英雄少女心 2020-12-30 02:26

I\'m wondering if there\'s a way to convert a boolean to an int without using if statements (as not to break the pipeline). For example, I could write

int bo         


        
相关标签:
12条回答
  • 2020-12-30 02:51

    You can't use a boolean other than in a if. However it does not mean that there will be a branch at the assembly level.

    If you check the compiled code of that method (by the way, using return b ? 1 : 0; compiles to the exact same instructions), you will see that it does not use a jump:

    0x0000000002672580: sub    $0x18,%rsp
    0x0000000002672587: mov    %rbp,0x10(%rsp)    ;*synchronization entry
    0x000000000267258c: mov    %edx,%eax
    0x000000000267258e: add    $0x10,%rsp
    0x0000000002672592: pop    %rbp
    0x0000000002672593: test   %eax,-0x2542599(%rip)        # 0x0000000000130000
                                                    ;   {poll_return}
    0x00000000025b2599: retq  
    

    Note: this is on hotspot server 7 - you might get different results on a different VM.

    0 讨论(0)
  • 2020-12-30 02:58

    You can use the ternary operator:

    return b ? 1 : 0;
    

    If this is considered an "if", and given this is a "puzzle", you could use a map like this:

    return new HashMap<Boolean, Integer>() {{
        put(true, 1);
        put(false, 0);
    }}.get(b);
    

    Although theoretically the implementation of HashMap doesn't need to use an if, it actually does. Nevertheless, the "if" is not in your code.

    Of course to improve performance, you would:

    private static Map<Boolean, Integer> map = new HashMap<Boolean, Integer>() {{
        put(true, 1);
        put(false, 0);
    }};
    

    Then in the method:

    return map.get(b);
    
    0 讨论(0)
  • 2020-12-30 02:59

    Use the ?: operator: ( b ? 1 : 0 )

    0 讨论(0)
  • 2020-12-30 03:03

    Otherwise, you could use the Apache Commons BooleanUtils.toInteger method which works like a charm...

    // Converts a boolean to an int specifying the conversion values.    
    static int  toInteger(boolean bool, int trueValue, int falseValue)
    
    // Converts a Boolean to an int specifying the conversion values.
    static int  toInteger(Boolean bool, int trueValue, int falseValue, int nullValue)
    
    0 讨论(0)
  • 2020-12-30 03:03

    I found a solution by framework. Use compare for Boolean.

    // b = Your boolean result
    // v will be 1 if b equals true, otherwise 0
    int v = Boolean.compare(b, false);
    
    0 讨论(0)
  • 2020-12-30 03:04

    Since you want no if / else solution your expression is perfect, though I would slightly change it

    int myint = Boolean.valueOf( bool ).compareTo( Boolean.FALSE );
    

    There is no object creation involved, Boolean.valueOf(boolean b) returns either Boolean.TRUE or Boolean.FALSE, see API

    0 讨论(0)
提交回复
热议问题