How do I make a generic enum rotator? It would be a generic version of next()
in this example.
public class TestEnum
{
enum Temperature { hot, cold };
public static void main(String[] args)
{
Temperature t = Temperature.hot;
Temperature t2 = next(t);
}
static Temperature next(Temperature t)
{
if (t.ordinal() == Temperature.values().length - 1)
return Temperature.values()[0];
else
return Temperature.values()[t.ordinal() + 1];
}
}
Edit: In the comments, @irreputable
suggests a superior solution. irreputable
if you post it as an answer I will select it. You might want to save time by copying this answer.
static <T extends Enum<T>> T next(T t)
{
int index = t.ordinal();
@SuppressWarnings("unchecked")
Enum<T>[] constants = t.getClass().getEnumConstants();
if (index == constants.length - 1)
{
@SuppressWarnings("unchecked")
T result = (T)constants[0];
return result;
}
else
{
@SuppressWarnings("unchecked")
T result = (T)constants[index + 1];
return result;
}
}