java Java枚举是否有增量运算符++?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17664445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an increment operator ++ for Java enum?
提问by TomBoo
Is it possible to implement the ++
operator for an enum?
是否可以++
为枚举实现运算符?
I handle the current state of a state machinewith an enum and it would be nice to be able to use the ++
operator.
我用枚举处理状态机的当前状态,如果能够使用++
运算符就好了。
回答by Bohemian
You can't "increment" an enum, but you can get the nextenum:
你不能“增加”一个枚举,但你可以得到下一个枚举:
// 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:
实现覆盖next()
方法的合理选择包括:
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
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'toverride it might be:
覆盖该方法可避免生成values()
数组以检查其长度的潜在成本。例如,next()
最后一个实例不覆盖它的实现可能是:
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.
在这里,两者ordinal()
和values()
(通常)都被调用了两次,这将比上面覆盖的版本执行成本更高。
回答by Andy Thomas
No. Java does not support customized operator overloading for any user-defined type, including enums.
不可以。Java 不支持任何用户定义的类型(包括枚举)的自定义运算符重载。
However, you could define a method in the enum class that returned the next enumerator.
但是,您可以在枚举类中定义一个返回下一个枚举器的方法。