简体   繁体   English

Java Enum 链接到另一个 Enum

[英]Java Enum linking to another Enum

I would like to have enumerator in Java having other enum as attribute.我想让 Java 中的枚举器具有其他枚举作为属性。

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

    private Direction opposite;

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

So I have different Direction, and for each I want to know the opposite.所以我有不同的方向,对于每个我想知道相反的方向。 It is working fine for Down and Right, but I can't initialize Up because Down is not known yet (same fort Left).它适用于 Down 和 Right,但我无法初始化 Up,因为 Down 还不知道(同一个堡垒 Left)。

How can I edit enum variables after initialisation ?初始化后如何编辑枚举变量?

Put your initialization in a static block:将您的初始化放在静态块中:

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() + ")";
    }
}

One of the possible solution - you can encapsulate this login within the method可能的解决方案之一 - 您可以将此登录封装在方法中

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

It will be the same interface for classes that will use this enum对于将使用此枚举的类,它将是相同的接口

Quick and dirty solution, put the initialization in a static block:快速而肮脏的解决方案,将初始化放在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;
  }
}

One trick is to leave the arguments as null s:一个技巧是将参数保留为null s:

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

and set the "opposite of the opposite" to this in the constructor:并在构造函数中将“相反的相反”设置为this

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

But this is merely a trick.但这只是一个伎俩。 I don't think it's good-looking code.我不认为这是好看的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM