非法前向引用和枚举

2022-08-31 14:55:50

我正在用java编写一个游戏,它由一个瓷砖网格组成。我无法直观地定义瓷砖的边缘以及它们如何相互关联,例如,要获得瓷砖的相反边缘,我希望能够键入 。但是,当使用枚举来定义这些边时,我最终不得不在 contstructor 中前向引用至少两个边:TOP.opposite()

public enum Edge {

   TOP(Edge.BOTTOM), //illegal forward reference
   BOTTOM(Edge.TOP),
   LEFT(Edge.RIGHT), //illegal forward reference
   RIGHT(Edge.LEFT);

   private Edge opposite;

   private Edge(Edge opp){
      this.opposite = opp;
   }

   public Edge opposite(){
      return this.opposite;
   }
}

有没有办法使用同样简单的枚举来解决这个问题?


答案 1

你可以这样做,这并不那么直观。

public enum Edge {
    TOP, BOTTOM, LEFT, RIGHT;
    private Edge opposite;

    static {
        TOP.opposite = BOTTOM;
        BOTTOM.opposite = TOP;
        LEFT.opposite = RIGHT;
        RIGHT.opposite = LEFT;
    }
    public Edge opposite(){
        return this.opposite;
    }
}

答案 2
enum Edge {
    TOP {
        @Override
        public Edge opposite() {
            return BOTTOM;
        }
    },
    BOTTOM {
        @Override
        public Edge opposite() {
            return TOP;
        }
    },
    LEFT {
        @Override
        public Edge opposite() {
            return RIGHT;
        }
    },
    RIGHT {
        @Override
        public Edge opposite() {
            return LEFT;
        }
    };

    public abstract Edge opposite();
}