Java claims that the sequence number of the initial value is 0. Is it possible to assume that when I create an enumeration as follows:
public enum Direction {MONDAY, TUESDAY, WEDNESDAY, THURSDAY, ...}
That the sequence number TUESDAY
always 1, then from WEDNESDAY
always 2, ...?
I will be more specific. I declare the listing:
public enum Direction {UP,RIGHT,DOWN,LEFT}
Now there is a way to rotate 90 degrees (clockwise). This is one line with ordinals:
direction = Direction.values()[direction.ordinal()+1 % Direction.values().length];
If I had not used ordinals, I would have to use switch statements or conditions:
switch (direction) { case LEFT:newdirection = Direction.UP; break; etc... }
There are several advantages to using ordinals:
- shorter code
- faster code (sloppy)
- if a direction is added (e.g.
DOWN_LEFT
), the implementation does not have to change if you put the new direction in the right place
What do you think?
Fatso source share