问题描述
我有两个数组:Walls 和 Neighbors.
I have two arrays: Walls and Neighbors.
public boolean[] walls = new boolean[4];
public Cell[] neighbors = new Cell[4];
我有一个枚举:
enum Dir
{
North,
South,
East,
West
}
现在,我希望能够通过墙壁或邻居的方向访问它们,这样我就不必传递一堆魔法索引了.
Now, I would like to be able to access walls or neighbors by their direction, so I don't have to pass around a bunch of magic indexes.
然而,当我阅读 Enum.ordinal() 的文档时,它说程序员几乎不会使用这种方法,这让我觉得不应该以这种方式使用它.
However, when I was reading the documentation for Enum.ordinal() it said that programmers will have almost no use for this method which made me think it shouldn't be used in this way.
我正在考虑做类似的事情:
I was thinking of doing something like:
List<Dir> availableDirections = new ArrayList<Dir>();
for(Dir direction : Dir.values())
if (!Neighbors[direction.ordinal()].Visited)
availableDirections.add(direction);
甚至:
return Neighbors[Dir.North.ordinal()];
我应该恢复对 NORTH、SOUTH、EAST、WEST 使用静态常量并将索引值设置为它们还是使用 Enum 的序数方法?
Should I revert to using static constants for NORTH, SOUTH, EAST, WEST with the index value set to them or use an Enum's ordinal method?
推荐答案
在切线问题上,为您的邻居使用 EnumMap 可能会更好:
On a tangential issue, it might be better to use an EnumMap for your neighbours:
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..
顺便说一句:按照惯例,枚举实例应该全部大写,
BTW: Enum instances should by convention be all caps,
enum Dir {
NORTH,
EAST,
SOUTH,
WEST
}
这篇关于在 Java 中使用 Enum 的序数值索引数组是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!