Java枚举是否有增量运算符++? [英] Is there an increment operator ++ for Java enum?

查看:139
本文介绍了Java枚举是否有增量运算符++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以为枚举实现 ++ 运算符吗?

Is it possible to implement the ++ operator for an enum?

我处理当前状态一个具有枚举的状态机,可以使用 ++ operator。

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

推荐答案

你不能增加枚举,但你可以获得下一个枚举:

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];
    }
}

所以你可以这样做:

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

您为执行被覆盖的 next() / code>方法包括:

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


  • return null; //没有下一个

  • return this; //在最后一个实例上加上

  • return values()[0]; //滚动到第一个

  • throw new RuntimeException(); //或类似NoSuchElementException的子类

  • 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

覆盖该方法避免了生成 values()数组来检查它的长度。例如, next()的最后一个实例不实现的实现可能是:

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];
}

这里, ordinal() values()(通常)被称为两次,这将比上面的覆盖版本执行成本更高。

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

这篇关于Java枚举是否有增量运算符++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆