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;
}
}
Try:
public class Test {
enum Temperature { hot, cold };
public static void main(String[] args) throws Exception
{
Temperature t = Temperature.hot;
Temperature t2 = next(t);
System.out.println(t2);
}
static <T extends Enum> T next(T t) throws Exception
{
Method values = t.getClass().getMethod("values");
if (t.ordinal() == ((T[])values.invoke(t)).length - 1)
return ((T[])values.invoke(t))[0];
else
return ((T[])values.invoke(t))[t.ordinal() + 1];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With