TomBoo TomBoo - 4 months ago 9
Java Question

Is there an increment operator ++ for Java enum?

Is it possible to implement the

++
operator for an enum?

I handle the current state of a state machine with an enum and it would be nice to be able to use the
++
operator.

Answer

You can't "increment" an enum, but you can get the next enum:

// MyEnum e;
MyEnum next = MyEnum.values()[e.ordinal() + 1];

But better would be to create an instance method on your enum.

Note well how the problematic next value is handled for the last enum instance, for which there is no "next" instance:

public enum MyEnum {

    Alpha,
    Bravo,
    Charlie {
        @Override
        public MyEnum next() {
            return null; // see below for options for this line
        };
    };

    public MyEnum next() {
        // No bounds checking required here, because the last instance overrides
        return values()[ordinal() + 1];
    }
}

So you could do this:

// MyEnum e;
e = e.next();

The reasonable choices you have for the implementation of the overidden next() method include:

  • return null; // there is no "next"
  • return this; // capped at the last instance
  • return values()[0]; // rollover to the first
  • throw new RuntimeException(); // or a subclass like NoSuchElementException

Overriding the method avoids the potential cost of generating the values() array to check its length. For example, an implementation for next() where the last instance doesn't override it might be:

public MyEnum next() {
    if (ordinal() == values().length - 1)
        throw new NoSuchElementException();
    return values()[ordinal() + 1];
}

Here, both ordinal() and values() are (usually) called twice, which will cost more to execute than the overridden version above.