7

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

Raffaeu
  • 6,694
  • 13
  • 68
  • 110
  • http://stackoverflow.com/a/17006263/4467208 – Murat Karagöz Dec 08 '15 at 15:22
  • I know that answer but I wanted a infinite solution capable to go back to the first item when reach the end of the array, so it's not a duplicate – Raffaeu Dec 08 '15 at 15:26
  • 1
    The question that this was marked with also wants to loop back to the first index, so technically it is a duplicate. I think my answer is a bit easier to read though :p – EpicPandaForce Dec 08 '15 at 15:28

1 Answers1

19

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];
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428