Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

Enumeration Classes

You saw in Chapter 3 how to define enumerated types in Java SE 5.0 and beyond. Here is a typical example:

public enum Size { SMALL, MEDIUM, LARGE, EXTRA_LARGE };

The type defined by this declaration is actually a class. The class has exactly four instances—it is not possible to construct new objects.

Therefore, you never need to use equals for values of enumerated types. Simply use == to compare them.

You can, if you like, add constructors, methods, and fields to an enumerated type. Of course, the constructors are only invoked when the enumerated constants are constructed. Here is an example.

enum Size

   private Size(String abbreviation) { this.abbreviation = abbreviation; }
   public String getAbbreviation() { return abbreviation; }

   private String abbreviation;

All enumerated types are subclasses of the class Enum. They inherit a number of methods from that class. The most useful one is toString, which returns the name of the enumerated constant. For example, Size.SMALL.toString() returns the string "SMALL".

The converse of toString is the static valueOf method. For example, the statement

Size s = (Size) Enum.valueOf(Size.class, "SMALL");

sets s to Size.SMALL.

Each enumerated type has a static values method that returns an array of all values of the enumeration. For example, the call

Size[] values = Size.values();

returns the array with elements Size.SMALL, Size.MEDIUM, Size.LARGE, and Size.EXTRA_LARGE.

The ordinal method yields the position of an enumerated constant in the enum declaration, counting from zero. For example, Size.MEDIUM.ordinal() returns 1.

The short program in Listing 5-5 demonstrates how to work with enumerated types.

Listing 5-5. EnumTest.java

 1. import java.util.*;
 3. /**
 4.  * This program demonstrates enumerated types.
 5.  * @version 1.0 2004-05-24
 6.  * @author Cay Horstmann
 7.  */
 8. public class EnumTest
 9. {
10.    public static void main(String[] args)
11.    {
12.       Scanner in = new Scanner(System.in);
13.       System.out.print("Enter a size: (SMALL, MEDIUM, LARGE, EXTRA_LARGE) ");
14.       String input = in.next().toUpperCase();
15.       Size size = Enum.valueOf(Size.class, input);
16.       System.out.println("size=" + size);
17.       System.out.println("abbreviation=" + size.getAbbreviation());
18.       if (size == Size.EXTRA_LARGE)
19.          System.out.println("Good job--you paid attention to the _.");
20.    }
21. }
23. enum Size
24. {
25.    SMALL("S"), MEDIUM("M"), LARGE("L"), EXTRA_LARGE("XL");
27.    private Size(String abbreviation) { this.abbreviation = abbreviation; }
28.    public String getAbbreviation() { return abbreviation; }
30.    private String abbreviation;
31. }
  • + Share This
  • 🔖 Save To Your Account