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

前端 未结 7 1245
不思量自难忘°
不思量自难忘° 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:33

    If you are not persisting the arrays or in any other way are making yourself dependent on different versions of your enum class, it's safe to use ordinal().

    If you want don't want to rely on the implicit ordering of the enum values, you could introduce a private index value:

    public enum Direction {
      NORTH(0),
      SOUTH(1),
      EAST(2),
      WEST(3);
    
      private int _index;
    
      private Direction (int index_)
      {
        _index = index_;
      }
    
      public int getIndex()
      {
        return _index;
      }
    }
    

    From here it's easy to both allow for easy lookup of index to Direction (By creating a Map in a static block for compact persistence; Do uniqueness check in static block etc.

提交回复
热议问题