【问题标题】:Java Enum linking to another EnumJava Enum 链接到另一个 Enum
【发布时间】:2023-03-22 06:26:01
【问题描述】:

我希望 Java 中的枚举器具有其他枚举作为属性。

public enum Direction {
    Up(Down),
    Down(Up),
    Left(Right),
    Right(Left);

    private Direction opposite;

    Direction(Direction opposite){
        this.opposite = opposite;
    }
}

所以我有不同的方向,对于每个我想知道相反的方向。 它适用于 Down 和 Right,但我无法初始化 Up,因为 Down 尚不清楚(同一个堡垒 Left)。

初始化后如何编辑枚举变量?

【问题讨论】:

    标签: java enums


    【解决方案1】:

    将你的初始化放在一个静态块中:

    public enum Direction {
        Up, Down, Left, Right;
    
        private Direction opposite;
    
        static {
            Up.setDirection(Down);
            Down.setDirection(Up);
            Left.setDirection(Right);
            Right.setDirection(Left);
        }
    
        private void setDirection(Direction opposite) {
            this.opposite = opposite;
        }
    
        public String toString() {
            return this.name() + " (" + opposite.name() + ")";
        }
    }
    

    【讨论】:

    • setDirection 有一个误导性的名称。 setOppositeDirection 或 setOpposite 会更好。
    【解决方案2】:

    一种可能的解决方案 - 您可以将此登录封装在方法中

    public Direction getOpposite() {
       switch (this) {
          case Up:
             return Down;
          case Down:
             return Up;
          case Left:
             return Right;
          case Right:
             return Left;
       }
       return null;
    }
    

    对于将使用此枚举的类来说,这将是相同的接口

    【讨论】:

      【解决方案3】:

      一个技巧是将参数保留为nulls:

      enum Direction {
          Up(null),
          Down(Up),
          Left(null),
          Right(Left);
      

      并在构造函数中将“对立面”设置为this

      Direction(Direction opposite){
          this.opposite = opposite;
          if (opposite != null) {
              opposite.opposite = this;
          }
      }
      

      但这只是一个技巧。我不认为这是好看的代码。

      【讨论】:

        【解决方案4】:

        快速而肮脏的解决方案,将初始化放在static 块中:

        public enum Direction {
          Up,
          Down,
          Left,
          Right;
        
        private Direction opposite;
        
        public Direction opposite() {
            return this.opposite;
        }
        
        static {
            Up.opposite = Down;
            Down.opposite = Up;
            Left.opposite = Right;
            Right.opposite = Left;
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2013-08-19
          • 1970-01-01
          • 2013-07-01
          • 1970-01-01
          • 2013-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多