...
Code Block | ||
---|---|---|
| ||
enum Hydrocarbon { METHANE(1), ETHANE(2), PROPANE(3), BUTANE(4), PENTANE(5), HEXANE(6), BENZENE(6), HEPTANE(7), OCTANE(8), NONANE(9), DECANE(10); private final int numberOfCarbons; Hydrocarbon(int carbons) { this.numberOfCarbons = carbons; } public int getNumberOfCarbons() { return numberOfCarbons; } } |
Applicability
It is acceptable to use the ordinals associated with an enumerated type when the order of the enumeration constants is standard and extra constants cannot be added. For example, the use of ordinals presents no problem with the following enumerated type:
Code Block |
---|
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
|
However, in general use Use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.
...
[JLS 2011] | |
[API 2011] | |
[Bloch 2008] | Item 31: Use instance fields instead of ordinals |