Java Enum Methods - return opposite direction enum

后端 未结 6 737
时光说笑
时光说笑 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:02

    Yes we do it all the time. You return a static instance rather than a new Object

     static Direction getOppositeDirection(Direction d){
           Direction result = null;
           if (d != null){
               int newCode = -d.getCode();
               for (Direction direction : Direction.values()){
                   if (d.getCode() == newCode){
                       result = direction;
                   }
               }
           }
           return result;
     }
    

提交回复
热议问题