Switch case for two INT variables

前端 未结 6 1350
生来不讨喜
生来不讨喜 2021-01-12 19:07

Consider the following code :

if (xPoint > 0 && yPoint > 0) {
    m_navigations = Directions.SouthEast;
}
else if (xPoint > 0 && yP         


        
6条回答
  •  星月不相逢
    2021-01-12 19:46

    boolean xNeg  = xPoint  < 0;
    boolean yNeg  = yPoint  < 0;
    boolean xZero = xPoint == 0;
    boolean yZero = yPoint == 0;
    

    We have four bits, we have 2^4 possibilities, an array of Directions may do the rest...

    int index =
       ((xNeg ?1:0)<<3)|
       ((yNeg ?1:0)<<2)|
       ((xZero?1:0)<<1)|
       ((yZero?1:0)<<0);
    Directions dir = directions[index];
    

    with directions a static final array of Directions initialized at class loading time.

    static final Directions[] directions = {
       Direction.NorthEast, // false, false, false, false ==> x  > 0 && y  > 0
       Direction.East,      // false, false, false, true  ==> x  > 0 && y == 0
       Direction.North,     // false, false, true , false ==> x == 0 && y  > 0
       ...
    }
    

    Indexing an array with an integer computed from ternaries, shift and or operators is less CPU consuming than a string concatenation used in a string switch and works well from Java 1.0.

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题