Converting Boolean to Integer in Java without If-Statements

后端 未结 12 1894
盖世英雄少女心
盖世英雄少女心 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: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() {{
        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 map = new HashMap() {{
        put(true, 1);
        put(false, 0);
    }};
    

    Then in the method:

    return map.get(b);
    

提交回复
热议问题