Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java get next Enum value or start from first [duplicate]

Tags:

java

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

like image 924
Raffaeu Avatar asked Dec 08 '15 15:12

Raffaeu


1 Answers

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];
}
like image 51
EpicPandaForce Avatar answered Oct 14 '22 07:10

EpicPandaForce