I noticed that the Java Enum Documentation has an ordinal method:
Returns the sequence number of this enumeration constant (its position in the enumeration declaration, where the zero constant is assigned to the original constant). Most programmers will not use this method. It is intended for use by complex enum-based data structures such as EnumSet and EnumMap.
I understand all the examples on the Internet that suggest not to be used ordinalfor indexing into an array, but instead EnumMap. Especially Point 33 Effective Java
But my question is: can it be used in my definition Enum? For example, my code is as follows:
public enum Direction {
NORTH(0, 1), NORTH_EAST(1, 1), EAST(1, 0), SOUTH_EAST(1, -1),
SOUTH(0, -1), SOUTH_WEST(-1, 1), WEST(-1, 0), NORTH_WEST(-1, 1);
private final int xOffset;
private final int yOffset;
private final static int DEGREES = 360;
private Direction(int xOffset, int yOffset) {
this.xOffset = xOffset;
this.yOffset = yOffset;
}
public Position move(Position position) {
return new Position(position.getX() + xOffset, position.getY() + yOffset);
}
public Direction rotate(int degrees) {
int length = Direction.values().length;
int index = (ordinal() + (degrees / (DEGREES / length))) % length;
return Direction.values()[index];
}
}
, ordinal(), ( ). . 90 NORTH EAST.
, , , , .
!