Java 5 Enums

From NovaOrdis Knowledge Base
Jump to navigation Jump to search

Externa

Internal

Overview

The standard way of representing an enumerated type in pre-5 Java was the "int Enum pattern":

public static final int COLOR_RED = 0;
public static final int COLOR_BLUE = 1;
public static final int COLOR_WHITE = 2;
...

Problems with this approach:

  • Not type safe any int value can be passed as a "color". There is no concept of "color" type.
  • No namespace you must prefix constants of an int enum with a string (in this case COLOR_) to avoid collisions with other int enum types.
  • Brittleness because int enums are compile-time constants, they are compiled into clients that use them. If a new constant is added between two existing constants or the order is changed, clients must be recompiled. If they are not, they will still run, but their behavior will be undefined.
  • Printed values are uninformative.

Java 5 added syntactic support for enumerated types:

public class Example {

    public enum Color { BLUE, RED, WHITE, BLACK };

    ....
}

The above declaration defines a full-fledged class, known as enum type.

When should we use enum?

Any time we need a fixed set of constants. That includes natural enumerated types (like the planets, days of the week, and suits in a card deck) as well as other sets where you know all possible values at compile time, such as choices on a menu, rounding modes, command line flags, and the like.

It is not necessary that the set of constants in an enum type stay fixed for all time. The feature was specifically designed to allow for binary compatible evolution of enum types.