使用Enum的序数值来索引Java中的数组是不好的做法吗?

Sco*_*r84 19 java enums

我有两个阵列:墙和邻居.

public boolean[] walls = new boolean[4];
public Cell[] neighbors = new Cell[4];
Run Code Online (Sandbox Code Playgroud)

我有一个枚举:

enum Dir
{
    North,
    South,
    East,
    West
}
Run Code Online (Sandbox Code Playgroud)

现在,我希望能够通过他们的方向访问墙壁或邻居,所以我不必传递一堆魔法索引.

但是,当我阅读Enum.ordinal()的文档时,它说程序员几乎没有使用这种方法,这让我认为它不应该以这种方式使用.

我在想做类似的事情:

    List<Dir> availableDirections = new ArrayList<Dir>();
    for(Dir direction : Dir.values())
        if (!Neighbors[direction.ordinal()].Visited)
            availableDirections.add(direction);
Run Code Online (Sandbox Code Playgroud)

甚至:

return Neighbors[Dir.North.ordinal()];
Run Code Online (Sandbox Code Playgroud)

我应该恢复使用设置为索引值的NORTH,SOUTH,EAST,WEST的静态常量还是使用Enum的序数方法?

too*_*kit 16

在一个切线问题上,为邻居使用EnumMap可能更好:

Map<Dir, Cell> neighbours = 
    Collections.synchronizedMap(new EnumMap<Dir, Cell>(Dir.class));

neighbours.put(Dir.North, new Cell());

for (Map.Entry<Dir, Cell> neighbour : neighbours.entrySet()) {
    if (neighbour.isVisited()) { ... }
}

etc..
Run Code Online (Sandbox Code Playgroud)

顺便说一句:按照惯例,枚举实例应该是全部大写,

enum Dir {
    NORTH,
    EAST, 
    SOUTH,
    WEST
}
Run Code Online (Sandbox Code Playgroud)

  • 和`EnumSet`为`wall`.可能不需要它同步. (2认同)

Mic*_*ers 13

文档只说大多数程序员都不会使用该方法.这是合法使用的一个案例.假设您的类同时控制枚举和数组,则没有理由担心ordinal()索引数组的方法(因为您始终可以使它们保持同步).

但是,如果你的使用变得更复杂,你可能会想要使用一个EnumMap,如同所建议的那样.

  • 虽然这是显示代码的有效案例,但大多数代码在某些时候都会被更改,这很容易使其成为无效的情况. (2认同)

Arn*_*ter 13

您还可以增强枚举(顺时针索引):

enum Dir
{
  NORTH(0),
  SOUTH(2),
  EAST(1),
  WEST(3);

  private final int index;

  private Dir(int index) {
    this.index = index;
  }

  public int getIndex() {
    return index;
  }

}
Run Code Online (Sandbox Code Playgroud)