Java language enumeration types have an ordinal() method that returns the numerical position of each enumeration constant in its class declaration.

According to the Java API, Class Enum<E extends Enum<E>> [API 2011], public final int ordinal()

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 and EnumMap.

The Java Language Specification, §8.9, "Enums" [JLS 2013], does not specify the use of ordinal() in programs. However, attaching external significance to the ordinal() value of an enum constant is error prone and should be avoided for defensive programming.

Noncompliant Code Example

This noncompliant code example declares enum Hydrocarbon and uses its ordinal() method to provide the result of the getNumberOfCarbons() method:

enum Hydrocarbon {
  METHANE, ETHANE, PROPANE, BUTANE, PENTANE,
  HEXANE, HEPTANE, OCTANE, NONANE, DECANE;

  public int getNumberOfCarbons() {
    return ordinal() + 1;
  }
}

Although this noncompliant code example behaves as expected, its maintenance is likely to be problematic. If the enum constants were reordered, the getNumberOfCarbons() method would return incorrect values. Furthermore, adding an additional BENZENE constant to the model would break the invariant assumed by the getNumberOfCarbons() method because benzene has six carbons, but the ordinal value 6 is already taken by HEXANE.

Compliant Solution

In this compliant solution, enum constants are explicitly associated with the corresponding integer values for the number of carbon atoms they contain:

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;
  }
}

The getNumberOfCarbons() 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 getNumberOfCarbons() 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 is permitted with the following enumerated type:

public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
                  THURSDAY, FRIDAY, SATURDAY }

In general, use of ordinals to derive integer values reduces the program's maintainability and can lead to errors in the program.

Bibliography

[API 2013]

Class Enum<E extends Enum<E>>

[Bloch 2008]Item 31, "Use Instance Fields Instead of Ordinals"
[JLS 2013]§8.9, "Enums"

 


6 Comments

  1. I didn't think that two different enum constants could be associated with the same value, but I just ran a test and they can.

    I've added some text saying this, and modified the CS to include BENZENE.

    I hope that's OK.

  2. I'm not sure i completely agree with this rule (or maybe this could be an "exception").  i've created various enums where the ordering of the values was significant (e.g. the ordering was related to severity or status in a state diagram).  in these situations, the ordinal values themselves weren't significant, just the relationship between them.

  3.            public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }

    • Using ordinal as an index for arrays could be counterproductive
    • This guideline also seems to be described in Effective Java - item 31, need confirmation and a reference
    1. I've dealt with the exception and the reference to Effective Java, but not the other two points as I wasn't sure about them.

      1. Item 33 Use EnumMap instead of Ordinal Indexing [Bloch 08] discusses why you should not use ordinal values as array indices. (Pg 161)

        1. Yeah, I see that.  Are you suggesting that we should include this in related guidelines, or that we should expand our rule or examples?  Both of the Josh Block rules seem to give more specific advice than ours.