Java: bool + int

前端 未结 2 805
孤街浪徒
孤街浪徒 2021-01-23 01:33

Is there a way to make Java work with boolean/integer addition and evaluation? More specificly, C++ has an appropriate feature which shortens many if statements.

         


        
2条回答
  •  遥遥无期
    2021-01-23 02:34

    Code is more often read than written. While you can use the ternary operator, the semantic of this boils down to only increasing count if x equals y. So the most readable way to write this would be to use:

    for (int i = 0; i < n; ++i)
       if (x == y) count++;
    

    Doing tricks like count += (x==y) in other languages is imho already bad practices since it obfuscates the logic. Optimize for reading, not writing.

提交回复
热议问题