To get the next enum value in a sequence in Java, you can use the values
method of the Enum
class and the ordinal
method to get the index of the current value.
Here is an example of how to get the next enum value in a sequence:
public enum Days { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Days currentDay = Days.MONDAY; Days nextDay = Days.values()[(currentDay.ordinal() + 1) % Days.values().length];Source:wtual.wwturi.com
The values
method returns an array of the values of the enum in the order they are declared, and the ordinal
method returns the index of the current value in the array. By adding 1 to the ordinal and taking the modulo of the result with the length of the array, we can get the next value in the sequence.
For example, if the currentDay
variable is MONDAY
, the ordinal
method will return 1, and the nextDay
variable will be assigned the value TUESDAY
. If the currentDay
variable is SATURDAY
, the ordinal
method will return 6, and the nextDay
variable will be assigned the value SUNDAY
.
Note that this approach only works if the enum values are in a sequence.