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

▼魔方 西西 提交于 2019-12-18 14:07:09

问题


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.


回答1:


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.




回答2:


No. Java does not support customized operator overloading for any user-defined type, including enums.

However, you could define a method in the enum class that returned the next enumerator.



来源:https://stackoverflow.com/questions/17664445/is-there-an-increment-operator-for-java-enum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!