Java Enum linking to another Enum

♀尐吖头ヾ 提交于 2020-08-19 12:17:11

问题


I would like to have enumerator in Java having other enum as attribute.

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).

How can I edit enum variables after initialisation ?


回答1:


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




回答2:


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



回答3:


Quick and dirty solution, put the initialization in a static block:

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;
  }
}



回答4:


One trick is to leave the arguments as nulls:

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

and set the "opposite of the opposite" to this in the constructor:

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.



来源:https://stackoverflow.com/questions/60372779/java-enum-linking-to-another-enum

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!