ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.

advertisement

AddThis Social Bookmark Button

Enums in Java (One More Time)

by John I. Moore, Jr.
04/23/2003

Unlike most modern languages, Java does not support the concept of user-defined enumerated types--enums. This article revisits the topic one more time, briefly defining what it means for a programming language to support enums and reviewing the strengths and weaknesses of two alternative approaches for Java. It then presents a mini-language for defining enums compactly. A small "compiler" that translates this mini-language into Java source code is provided as a resource accompanying this article.

Enumerated Types

I first encountered user-defined enumerated types in the late 1970s when I switched from FORTRAN to Pascal. Pascal, Ada, and C++, the programming languages that dominated my life before I switched to Java in 1997, have always had this feature. Even though Java is currently my programming language of choice, I've had to adjust to the lack of enums.

What is an enumerated type? Consider, for example, this C++ code fragment:

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

This declaration provides a user-defined type named Day. It enumerates all of the possible values for a variable of this type.

Related Reading

Java Data Objects
By David Jordan, Craig Russell

Different programming languages take slightly different approaches, but the most desirable characteristics of an enumerated type facility in a programming language are:

  1. Type safety.
  2. Compact, efficient declaration of enumerated values.
  3. Seamless integration with other language features.
  4. Runtime efficiency.

Let's consider these characteristics one at a time.

1. Type Safety

An enum declaration should create a new type that is distinct from all other types, including primitive types and all other enum types currently in scope. In particular, when it comes to assignments or function arguments, variables of type int and variables of an enumerated type cannot be freely interchanged without explicit casts. The compiler should be able to enforce this. For example, given the above enum declaration and a method with the following specification:

public void foo(Day);

the compiler would report an error if we attempt to call this method with an argument of type int, as in

foo(4);    // compilation error

Unlike Pascal, Ada, and C++, C enums are not simply like ints, they are ints. Thus, C also fails to support enums, according to my criteria.

2. Compact, Efficient Declaration of Enumerated Values

The amount of typing effort to create the enum type should be minimal. For example, compare the above enum declaration with the following Java alternative:

public static final int SUNDAY    = 0;
public static final int MONDAY    = 1;
public static final int TUESDAY   = 2;
public static final int WEDNESDAY = 3;
public static final int THURSDAY  = 4;
public static final int FRIDAY    = 5;
public static final int SATURDAY  = 6;

The enum declaration is compact and efficient, but the Java constant declarations are not. Enums with larger numbers of values provide even better examples. While compact, efficient declaration of enumerated values is important, especially when attempting to get programmers to use the language feature, this criterion is of lesser importance than the other three.

3. Seamless Integration with Other Language Features

Language operators (such as assignment, equality, and less than) should work for enums. Enums should be usable as array indices and in control flow constructs such as the case alternatives of switch statements. For example, I would like to be able to write a statement similar to the following:

for (Day d = SUNDAY;  d <= SATURDAY;  ++d) {
    switch(d) {
        case MONDAY:     ...;
            break;
        case TUESDAY:    ...;
            break;
        case WEDNESDAY:  ...;
            break;
        case THURSDAY:   ...;
            break;
        case FRIDAY:     ...;
            break;
        case SATURDAY:
        case SUNDAY:    ...;
    }
}

I can do this if the enums are defined as integer constants as in characteristic 2, above, but not if they are objects. For Java, methods such as equals() and compareTo() provide suitable alternatives to the relational operators, but there are no good non-int alternatives for array indices and switch statements.

4. Runtime Efficiency

Enums should have performance characteristics at the level of primitive integer types. There should be no runtime penalty for using enums over ints.

A language fully supports enumerated types if it meets all four of the above criteria. Thus, Pascal, Ada, and C++ all support enumerated types, while Java does not. As indicated in Resources below, enum support is one of the most requested Java language extensions.

James Gosling obviously knew about enums when he designed Java, so their omission must have been intentional. Perhaps he did not fully appreciate their value, or perhaps he made a conscious decision to promote polymorphism by discouraging processing based on multi-way branching, as is often associated with enums. Whatever the reason, we are (still!) forced to live without them in Java.

Pages: 1, 2, 3

Next Pagearrow