Java states that the ordinal of the initial value is 0. Can I assume that when I create an enumeration like this :
public enum Direction {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, ...}
That the ordinal of TUESDAY is always 1, that of WEDNESDAY always 2, …?
I’ll be a bit more specific. I’m declaring an enumeration :
public enum Direction {UP,RIGHT,DOWN,LEFT}
Now there’s a method to turn 90 degrees (clockwise). It’s one line with ordinals :
direction = Direction.values()[direction.ordinal()+1 % Direction.values().length];
If I wouldn’t use ordinals I would have to use switch statements or conditions :
switch (direction) {
case LEFT:newdirection = Direction.UP;
break;
etc...
}
There are a couple advantages to using ordinals :
- shorter code
- faster code (negligeable)
- if a direction is added (for example
DOWN_LEFT) the implementation doesn’t necessarily have to change if you put the new direction at the right spot
What do you think?
Yes – see javadoc: