Datasheet

Enumerations
Java introduces enumeration support at the language level in the JDK 5 release. An enumeration is an
ordered list of items wrapped into a single entity. An instance of an enumeration can take on the value of
any single item in the enumeration’s list of items. The simplest possible enumeration is the
Colors enum
shown here:
public enum Colors { red, green, blue }
They present the ability to compare one arbitrary item to another, and to iterate over the list of defined
items. An enumeration (abbreviated
enum in Java) is a special type of class. All enumerations implicitly
subclass a new class in Java,
java.lang.Enum. This class cannot be subclassed manually.
There are many benefits to built-in support for enumerations in Java. Enumerations are type-safe and
the performance is competitive with constants. The constant names inside the enumeration don’t need to
be qualified with the enumeration’s name. Clients aren’t built with knowledge of the constants inside
the enumeration, so changing the enumeration is easy without having to change the client. If constants
are removed from the enumeration, the clients will fail and you’ll receive an error message. The names
of the constants in the enumeration can be printed, so you get more information than simply the ordinal
number of the item in the list. This also means that the constants can be used as names for collections
such as
HashMap.
Because an enumeration is a class in Java, it can also have fields and methods, and implement interfaces.
Enumerations can be used inside
switch statements in a straightforward manner, and are relatively
simple for programmers to understand and use.
Here’s a basic
enum declaration and its usage inside a switch statement. If you want to track what oper-
ating system a certain user is using, you can use an enumeration of operating systems, which are
defined in the
OperatingSystems enum. Note that because an enumeration is effectively a class, it can-
not be public if it is in the same file as another class that is public. Also note that in the
switch state-
ment, the constant names cannot be qualified with the name of the enumeration they are in. The details
are automatically handled by the compiler based on the type of the
enum used in the switch clause:
import java.util.*;
enum OperatingSystems {
windows, unix, linux, macintosh
}
public class EnumExample1 {
public static void main(String args[])
{
OperatingSystems os;
os = OperatingSystems.windows;
switch(os) {
case windows:
System.out.println(“You chose Windows!”);
break;
case unix:
System.out.println(“You chose Unix!”);
break;
24
Part I: Thinking Like a Java Developer
05_777106 ch01.qxp 11/28/06 10:43 PM Page 24