我想让 Java 中的枚举器具有其他枚举作为属性。
public enum Direction {
Up(Down),
Down(Up),
Left(Right),
Right(Left);
private Direction opposite;
Direction(Direction opposite){
this.opposite = opposite;
}
}
Run Code Online (Sandbox Code Playgroud)
所以我有不同的方向,对于每个我想知道相反的方向。它适用于 Down 和 Right,但我无法初始化 Up,因为 Down 还不知道(同一个堡垒 Left)。
初始化后如何编辑枚举变量?
小智 7
将您的初始化放在静态块中:
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() + ")";
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
可能的解决方案之一 - 您可以将此登录封装在方法中
public Direction getOpposite() {
switch (this) {
case Up:
return Down;
case Down:
return Up;
case Left:
return Right;
case Right:
return Left;
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
对于将使用此枚举的类,它将是相同的接口