Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an increment operator ++ for Java enum? [duplicate]

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.

like image 894
TomBoo Avatar asked Jul 15 '13 21:07

TomBoo


People also ask

Can we increment enum?

Enums are always assigned numeric values when they are stored. The first value always takes the numeric value of 0, while the other values in the enum are incremented by 1.

Can enum have duplicates?

Duplicates in enum type can be done in 2 ways : Duplicate enum members (2 or more members with same name) 2 or more members with same value.

Can we clone enum in Java?

The java. lang. Enum. clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.

Can an enum extend another?

Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.


1 Answers

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.

like image 164
Bohemian Avatar answered Sep 19 '22 08:09

Bohemian