在枚举类型上实现`next`和`previous`的最好方式是什么? [英] What's the best way to implement `next` and `previous` on an enum type?
问题描述
枚举E {
A,B,C;
}
如这个答案通过 lucasmo ,枚举值存储在静态数组中订单它们被初始化,然后您可以稍后使用 E.values()
检索(克隆)该数组。
现在假设我想实现 E#getNext
和 E#getPrevious
,以便所有以下表达式求值到 true
:
EAgetNext()== EB
EBgetNext()== EC
ECgetNext()== EA
EAgetPrevious()== EC
EBgetPrevious()== EA
EC getPrevious()== EB
我目前实现的 getNext
如下:
public E getNext(){
E [] e = );
int i = 0; (; e [i]!= this; i ++)
i ++;
i%= e.length;
return e [i];
}
和类似的方法getPrevious
。
但是,这段代码似乎很麻烦(例如,空为
循环,可争论滥用反变量,并且在最坏情况下可能会出现错误(思考反思,可能)。
实现 getNext
和 getPrevious
Java 7中枚举类型的方法?
注意:我不要这个问题是主观的,我对最佳实现的要求是要求实施速度最快,
尝试这样:
public static enum A {
X,Y,Z;
private static A [] vals = values();
public A next()
{
return vals [(this.ordinal()+ 1)%vals.length];
}
执行 previous()
作为一个练习,但回想起 a%b 可以返回的问题/ 4403542 / how-do-java-do-mod-calculation-with-negative-numbers?lq = 1一个负数。
编辑:建议,创建一个私人静态副本的 values()
array,以避免数组复制每次 next()
或 previous()
被调用。
Suppose I have an enum:
enum E {
A, B, C;
}
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()
.
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
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];
}
and a similar method for getPrevious
.
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).
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.
Try this:
public static enum A {
X, Y, Z;
private static A[] vals = values();
public A next()
{
return vals[(this.ordinal()+1) % vals.length];
}
Implementation of previous()
is left as an exercise, but recall that in Java, the modulo a % b
can return a negative number.
EDIT: 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屋!