我有两个阵列:墙和邻居.
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)
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)
| 归档时间: |
|
| 查看次数: |
23337 次 |
| 最近记录: |