...
In this compliant solution, enum
constants are explicitly associated with the corresponding integer values for the number of carbon atoms they contain. Consequently, the getNumberOfCarbon()
method no longer uses the ordinal()
to discover the number of carbon atoms for each value. Different enum
constants may be associated with the same value, as shown for HEXANE
and BENZENE
. Furthermore, this solution lacks any dependence on the order of the enumeration; the getNumberOfCarbon()
method would continue to work even if the enumeration were reordered.
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; } } |
Consequently, the getNumberOfCarbon()
method no longer uses the ordinal()
to discover the number of carbon atoms for each value. Different enum
constants may be associated with the same value, as shown for HEXANE
and BENZENE
. Furthermore, this solution lacks any dependence on the order of the enumeration; the getNumberOfCarbon()
method would continue to work even if the enumeration were reordered.
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 little problem is permitted with the following enumerated type:
...