So, I recently read this post and I want to do effectively the same thing.
I didn’t really care about “ugliness”, etc. so I implemented one of the methods like so:
public enum Day {
Monday(1),
Tuesday(2),
Wednesday(3),
Thursday(4),
Friday(5),
Saturday(6),
Sunday(7);
public final int id;
Day(int id) {
this.id = id;
}
public static Day getByID(int id) {
Day d = null;
for (Day dTemp : Day.values())
{
if (id == dTemp)
{
d = dTemp;
break;
}
}
return d;
}
public Day getNext() {
return values()[(ordinal()+1)%values().length];
}
public Day getPrev() {
return values()[(ordinal()-1)%values().length];
}
}
But, the problem with it is in the if statement when I do:
if (id == dTemp)
It says that they are incompatible types. What should I do to fix it?
Use
if ( id == dTemp.id ). Enums are classes and enum values are objects not ints and thus can’t be cast (neither explicitly nor implicitly) to anint.Alternatively, note that enums have an ordinal, i.e. an id of their position. In your example,
Mondaywould have the ordinal 0 andSundaywould have the ordinal 6. You access the ordinal by calling theordinal()method.Thus if
idis one-based you could do the following instead:Note that you might want to cache
Day.values()in a private static variable and access that cached array then.Btw, where’s the string you mention in your question?