Java language enumeration types have an ordinal()
method , which that returns the numerical position of each enumeration constant in its class declaration.
Wiki Markup |
---|
The _Java Language Specification_ \[java:[JLS 2005|AA. References#JLS 05]\] [§8.9, "Enums,"|http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9] does not specify the use of {{ordinal()}} in programs. However, using the {{ordinal()}} method to derive the value associated with an {{enum}} constant is error- prone and should be avoided. |
...
Code Block | ||
---|---|---|
| ||
enum Hydrocarbon { METHANE, ETHANE, PROPANE, BUTANE, PENTANE, HEXANE, HEPTANE, OCTANE, NONANE, DECANE; public int getNumberOfCarbons() { return ordinal() + 1; } } |
While Although this noncompliant code example works, its maintenance is susceptible to vulnerabilities. If the enum
constants were reordered, the getNumberOfCarbon()
method would return incorrect values. Also, BENZENE
- — which also has 6 carbons - — cannot be added without violating the current enum
design.
Compliant Solution
In this compliant solution, enum
constants are explicitly associated with the corresponding integer values for the number of carbon atoms they contain.
...
INT09-CPP. Ensure enumeration constants map to unique values | ||||
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="5884f1f215349c24-f2ec1f35-4bd14374-9e089108-8343d644d872b74f3be8f51e"><ac:plain-text-body><![CDATA[ | [ISO/IEC TR 24772:2010 | http://www.aitcnet.org/isai/] | "Enumerator Issues [java:CCB]" | ]]></ac:plain-text-body></ac:structured-macro> |
...
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="333eb8369512187c-ad916fdb-48b54ae3-8070b846-da0c518444d946b58b46d899"><ac:plain-text-body><![CDATA[ | [java:[JLS 2005 | AA. References#JLS 05]] | [§8.9, "Enums" | http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.9] | ]]></ac:plain-text-body></ac:structured-macro> |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="2a0f967c18d18c01-7d3aeeda-4ab04c65-a334a38c-de38f63c3726ab81cc340a3d"><ac:plain-text-body><![CDATA[ | [java:[API 2006 | AA. References#API 06]] | [Enum | http://download.oracle.com/javase/6/docs/api/java/lang/Enum.html] | ]]></ac:plain-text-body></ac:structured-macro> |
...