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.
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.
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.
The java. lang. Enum. clone() method guarantees that enums are never cloned, which is necessary to preserve their "singleton" status.
Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
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.
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