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

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

    The JavaDoc says

    Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as EnumSet and EnumMap.

    I think they want to say that most programmers will prefer using an EnumMap or EnumSet over manually indexing into an array. They certainly don't mean that you should substitute a couple of integer variables for your enum, as you would lose type safety in doing so.

    If you need the flexibility to be able to reorder the enum constants without affecting the order in the array you can isolate the index into another field of the enum as has been described by Arne.

提交回复
热议问题