4

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 ?

Nicktar
5,5851 gold badge31 silver badges43 bronze badges
asked Feb 24, 2020 at 9:22
0

4 Answers 4

7

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() + ")";
 }
}
D. Lawrence
9591 gold badge10 silver badges23 bronze badges
answered Feb 24, 2020 at 9:36
Sign up to request clarification or add additional context in comments.

1 Comment

setDirection has a misleading name. setOppositeDirection or setOpposite would be better.
5

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

answered Feb 24, 2020 at 9:38

Comments

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;
 }
}
answered Feb 24, 2020 at 9:36

Comments

3

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.

answered Feb 24, 2020 at 9:36

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.