Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assume that Java enumerations auto-increment by 1?

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?

like image 482
Benjamin Ortuzar Avatar asked Mar 08 '12 14:03

Benjamin Ortuzar


People also ask

Can you increment an enum in Java?

Java allows you to define enums as full-blown object types. As a result, you cannot simply increment it.

Can an enum be incremented?

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.

Does Java enum start 0?

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.

Are enums 0 based?

The default value of an uninitialized enumeration, just like other value types, is zero.


2 Answers

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).

like image 196
assylias Avatar answered Nov 11 '22 01:11

assylias


Yes - but your code should not rely on it because then it will break when someone inserts Caturday.

like image 37
Michael Borgwardt Avatar answered Nov 11 '22 02:11

Michael Borgwardt