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

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

    i strongly recommend against it because the Ordinal value is based on the order in your java code.

    The use of ordinal() will make you code very hard to maintain, especially if some form of persistence enters the equation.

    for example if you decide to add diagonal directions like NORTH_WEST, SOUTH_EAST. if you are using ordinal(), you must add these at the bottom of your list or else what used to be SOUTH might become NORTH.

    ie you can change your enyum to without (possibly) changing functionality

    N  (is now 0 was 0) 
    NE (is now 1) 
    E (is now 2 was 1) 
    SE (is now 3 ) 
    S  (is mow 4 was 2) 
    SW (is now 5) 
    W  (is now 6 was 3)
    

提交回复
热议问题