Boh*_*ian 47
你不能"增加"枚举,但你可以得到下一个枚举:
// MyEnum e;
MyEnum next = MyEnum.values()[e.ordinal() + 1];
Run Code Online (Sandbox Code Playgroud)
但更好的方法是在枚举上创建一个实例方法.
请注意如何为最后一个enum实例处理有问题的下一个值,因为没有"next"实例:
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];
}
}
Run Code Online (Sandbox Code Playgroud)
所以你可以这样做:
// MyEnum e;
e = e.next();
Run Code Online (Sandbox Code Playgroud)
您对实施重叠next()方法的合理选择包括:
return null; // there is no "next"return this; // capped at the last instancereturn values()[0]; // rollover to the firstthrow new RuntimeException(); // or a subclass like NoSuchElementException覆盖该方法避免了生成values()阵列以检查其长度的潜在成本.例如,next()最后一个实例不覆盖它的实现可能是:
public MyEnum next() {
if (ordinal() == values().length - 1)
throw new NoSuchElementException();
return values()[ordinal() + 1];
}
Run Code Online (Sandbox Code Playgroud)
在这里,无论是ordinal()和values()(通常)称为两次,这将花费更多的不是上面的重写版本执行.
| 归档时间: |
|
| 查看次数: |
11606 次 |
| 最近记录: |