I have an enum in Java as following:
public enum Cars
{
Sport,
SUV,
Coupe
}
And I need to get the next value of the enum. So, assuming I have a variable called myCurrentCar:
private Cars myCurrentCar = Cars.Sport;
I need to create a function that when called set the value of myCurrentCar to the next value in the enum. If the enum does not have anymore values, I should set the variable to the first value of the enum. I started my implementation in this way:
public Cars GetNextCar(Cars e)
{
switch(e)
{
case Sport:
return SUV;
case SUV:
return Coupe;
case Coupe:
return Sport;
default:
throw new IndexOutOfRangeException();
}
}
Which is working but it's an high maitenance function because every time I modify the enum list I have to refactor the function. Is there a way to split the enum into an array of strings, get the next value and transform the string value into the original enum? So in case I am at the end of the array I simply grab the first index
Yeah sure, it goes like this
public Cars getNextCar(Cars e)
{
int index = e.ordinal();
int nextIndex = index + 1;
Cars[] cars = Cars.values();
nextIndex %= cars.length;
return cars[nextIndex];
}
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