Java Enum Methods - return opposite direction enum

后端 未结 6 741
时光说笑
时光说笑 2020-11-27 10:34

I would like to declare an enum Direction, that has a method that returns the opposite direction (the following is not syntactically correct, i.e, enums cannot be instantiat

6条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 11:00

    public enum Direction {
        NORTH, EAST, SOUTH, WEST;
    
        public Direction getOppositeDirection(){
            return Direction.values()[(this.ordinal() + 2) % 4];
        }
    }
    

    Enums have a static values method that returns an array containing all of the values of the enum in the order they are declared. source

    since NORTH gets 1, EAST gets 2, SOUTH gets 3, WEST gets 4; you can create a simple equation to get the opposite one:

    (value + 2) % 4

提交回复
热议问题