使用枚举的序数值对Java中的数组进行索引是不好的做法吗? [英] Is it bad practice to use an Enum's ordinal value to index an array in Java?
问题描述
我有两个数组:墙壁和邻居。
public boolean [] walls = new boolean [
public Cell [] neighbors = new Cell [4];
我有一个枚举:
枚举目录
{
北,
南,
东,
西
}
现在,我想通过他们的方向访问墙壁或邻居,所以我不必传递但是,当我正在阅读Enum.ordinal()的文档时,它表示,程序员几乎没有使用这种方法,这让我想起了不应该以这种方式使用。
我在想这样做:
列表<目录> 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使用静态常量,索引值设置为他们或使用枚举的顺序方法?
在一个切入点的问题上,为邻居使用EnumMap可能会更好:
地图<目录,单元格> neighbors =
Collections.synchronizedMap(new EnumMap< Dir,Cell>(Dir.class));
neighbours.put(Dir.North,new Cell());
for(Map.Entry< Dir,Cell> neighbor:neighbours.entrySet()){
if(neighbour.isVisited()){...}
}
等..
BTW:按照惯例,
枚举目录{
NORTH,
EAST,
SOUTH,
WEST
}
I have two arrays: Walls and Neighbors.
public boolean[] walls = new boolean[4];
public Cell[] neighbors = new Cell[4];
and I have an Enum:
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.
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);
or even:
return Neighbors[Dir.North.ordinal()];
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?
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中的数组进行索引是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!