Is it bad practice to use an Enum's ordinal value to index an array in Java?

前端 未结 7 1247
不思量自难忘°
不思量自难忘° 2020-12-05 10:49

I have two arrays: Walls and Neighbors.

public boolean[] walls = new boolean[4];
public Cell[] neighbors = new Cell[4];

and I have an Enum:

7条回答
  •  感动是毒
    2020-12-05 11:23

    On a tangential issue, it might be better to use an EnumMap for your neighbours:

    Map neighbours = 
        Collections.synchronizedMap(new EnumMap(Dir.class));
    
    neighbours.put(Dir.North, new Cell());
    
    for (Map.Entry neighbour : neighbours.entrySet()) {
        if (neighbour.isVisited()) { ... }
    }
    
    etc..
    

    BTW: Enum instances should by convention be all caps,

    enum Dir {
        NORTH,
        EAST, 
        SOUTH,
        WEST
    }
    

提交回复
热议问题