Illegal Forward Reference and Enums

前端 未结 11 1447
-上瘾入骨i
-上瘾入骨i 2020-12-08 09:46

I\'m programming a game in java which is made up of a grid of tiles. I wan\'t to be able to inuitively define the edges of the tiles and how they relate to each other, e.g.

11条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 10:03

    You can create a static Map where key is the original enum and the value the opposite edge. Initialize it in a static block and the return the mapping from the opposite() method.

    private static Map oppostiteMapping;
    
    static {
      oppositeMapping = new EnumMap();
      oppositeMapping.put(TOP, BOTTOM);
      ...
    }
    
    public Edge opposite() {
        return oppositeMapping.get(this);
    } 
    

    EDIT: as proposed in comment better to use EnumMap, so I upgraded accordingly

    Btw. this approach is generally useful when you create something like static fromString() method etc.

提交回复
热议问题