Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Added an exception (under Applicability) and a reference to Effective Java

...

Code Block
bgColor#ccccff
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]

§8.9, "Enums"

[API 2011]

Class Enum<E extends Enum<E>>

[Bloch 2008]Item 31: Use instance fields instead of ordinals