How to cycle through the values of an Enum in Java

Here’s a quick little trick. I needed to advance my variable to the next value in an Enum. I found this can be done using the values and ordinal built-in members. This version wraps around to the beginning when you reach the end.

Here’s the code:

private enum Direction { NORTH, EAST, SOUTH, WEST;
public Direction getNext() {
return values()[(ordinal() + 1) % values().length];
}
};

Here’s an example of how to use it:

private Direction currentDirection = Direction.NORTH;

public void turn() {
currentDirection = currentDirection.getNext();
}