Consider the following code :
if (xPoint > 0 && yPoint > 0) {
m_navigations = Directions.SouthEast;
}
else if (xPoint > 0 && yP
-
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.
- 热议问题