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;
while (e[i] != this) i++;
i++; // next!
i %= e.length;
return e[i];
}
and a similar method for getPrevious
.
However, it seems unfortunate that this code takes time linear in the number of enum values.
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 enum A {
X, Y, Z;
private static final 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.