在枚举类型上实现 `next` 和 `previous` 的最佳方法是什么? [英] What's the best way to implement `next` and `previous` on an enum type?
问题描述
假设我有一个枚举:
enum E {
A, B, C;
}
如这个答案中所示,lucasmo,枚举值按照它们被初始化的顺序存储在一个静态数组中,你以后可以用 E.values()
检索(克隆)这个数组.
As shown in this answer by lucasmo, enum values are stored in a static array in the order that they are initialized, and you can later retrieve (a clone of) this array with E.values()
.
现在假设我想实现 E#getNext
和 E#getPrevious
使得以下所有表达式的计算结果为 true
:>
Now suppose I want to implement E#getNext
and E#getPrevious
such that all of the following expressions evaluate to true
:
E.A.getNext() == E.B
E.B.getNext() == E.C
E.C.getNext() == E.A
E.A.getPrevious() == E.C
E.B.getPrevious() == E.A
E.C.getPrevious() == E.B
我当前对 getNext
的实现如下:
My current implementation for getNext
is the following:
public E getNext() {
E[] e = E.values();
int i = 0;
for (; e[i] != this; i++)
;
i++;
i %= e.length;
return e[i];
}
以及getPrevious
的类似方法.
然而,这段代码充其量看起来很麻烦(例如,空"for
循环,有争议的滥用计数器变量,最坏的情况下可能是错误的(思考反射,可能).
However, this code seems cumbersome at best (e.g., "empty" for
loop, arguable abuse of a counter variable, and potentially erroneous at worst (thinking reflection, possibly).
在 Java 7 中为枚举类型实现 getNext
和 getPrevious
方法的最佳方法是什么?
What would be the best way to implement getNext
and getPrevious
methods for enum types in Java 7?
注意:我不希望这个问题是主观的.我对最佳"实现的要求是要求最快、最干净和最易于维护的实现的简写.
NOTE: I do not intend this question to be subjective. My request for the "best" implementation is shorthand for asking for the implementation that is the fastest, cleanest, and most maintainable.
推荐答案
试试这个:
public static enum A {
X, Y, Z;
private static A[] vals = values();
public A next()
{
return vals[(this.ordinal()+1) % vals.length];
}
previous()
的实现留作练习,但请记住 在Java中,模a % b
可以返回一个负数.
Implementation of previous()
is left as an exercise, but recall that in Java, the modulo a % b
can return a negative number.
按照建议,制作 values()
数组的私有静态副本,以避免每次 next()
或 previous()
被调用.
As suggested, make a private static copy of the values()
array to avoid array copying each time next()
or previous()
is called.
这篇关于在枚举类型上实现 `next` 和 `previous` 的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!