Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum linking to another Enum

Tags:

java

enums

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 ?

like image 263
Mister Aqua Avatar asked Dec 01 '22 13:12

Mister Aqua


2 Answers

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() + ")";
    }
}
like image 186
mayamar Avatar answered Dec 04 '22 16:12

mayamar


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

like image 28
Pankratiev Alexander Avatar answered Dec 04 '22 17:12

Pankratiev Alexander