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 :
DOWN_LEFT
) the implementation doesn't necessarily have to change if you put the new direction at the right spotWhat do you think?
Java allows you to define enums as full-blown object types. As a result, you cannot simply increment it.
Each of the enumerators has a constant integer value. The default is that the first enumerator's value is 0, and each enumerator succeeding is incremented by one. However, you can specify any of them.
The enum constants have an initial value which starts from 0, 1, 2, 3, and so on. But, we can initialize the specific value to the enum constants by defining fields and constructors. As specified earlier, Enum can have fields, constructors, and methods.
The default value of an uninitialized enumeration, just like other value types, is zero.
Yes - see javadoc:
Returns the ordinal of this enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero).
Yes - but your code should not rely on it because then it will break when someone inserts Caturday.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With