CHAPTER 3 ■ DATA TYPES
■ Caution Do not write collections of constants this way. They can be compared to int values, and that's almost
certain to be the wrong thing to do. That's why Java has enumerations.The enumeration value, Direction.NORTH,
can't be treated as an integer (not even by accident), whereas the constant, NORTH, can be. Also, constants are
static and final (and often public). Enumerations remove the need for those modifiers, which gives us greater
flexibility when using enumerations.
Each enum is actually a class. (You might have noticed that its declaration syntax is similar to a class.)
All enum objects implicitly extend java.lang.Enum. That lets us make more meaningful enums than just
lists of constants. To continue with our example, we can set the degrees for each direction, as shown in
Listing 3-13.
Listing 3-13. Enum with more information
public enum Direction {
NORTH (0),
EAST (90),
SOUTH (180),
WEST (270);
private final int degrees;
Direction(int degrees) {
this.degrees = degrees;
}
public int getDegrees() {
return degrees;
}
}
From there, we can write code to get the additional information associated with each value in the
enumeration, as shown in Listing 3-14.
Listing 3-14. Getting details from an enum
for (Direction d : Direction.values()) {
System.out.println(d + " is " + d.degrees + "degrees.");
}
We can also write methods that work with the enumeration's values. For example, we can write a
method that, given a direction in degrees, tells you which cardinal direction is closest. Listing 3-15 shows
one way to write such a method.