...
According to the Java API, Class Enum<E extends Enum<E>> [API 2011], public final int ordinal()
Returns returns the ordinal of the enumeration constant (its position in its enum declaration, where the initial constant is assigned an ordinal of zero). Most programmers will have no use for this method. It is designed for use by sophisticated enum-based data structures, such as
EnumSet
andEnumMap
.
...
In this compliant solution, enum
constants are explicitly associated with the corresponding integer values for the number of carbon atoms they contain. :
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; } } |
...
However, in general, use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.
Related Guidelines
...
Bibliography
[API 2011] | |
[Bloch 2008] | Item 31, "Use Instance Fields Instead of Ordinals" |
[JLS 2011] | §8.9, "Enums" |
...