|
Helping ordinary people create extraordinary websites! |
Getting Started with Enumerated TypesBy Brett McLaughlin2005-04-22
Enums and Collections Those of you familiar with the public static final approach to coding have probably already moved on to using enumerated values as keys to maps. For the rest of you who don't know what this means, take a look at Listing 9, which is an example of common error messages that can pop up when working with Ant build files: Listing 9. Ant status codes package com.oreilly.tiger.ch03;Having some human-readable error message assigned to each status code would allow you to look up the appropriate error message and echo it back out to the console when Ant supplies one of the codes. This is a great use-case for a Map, in which each key of the Map is one of these enumerated values, and each value is the error message for that key. Listing 10 illustrates how this works: Listing 10. Maps of enums public void testEnumMap(PrintStream out) throws IOException {
This code uses both generics (see Resources) and the new EnumMap construct to create a new map. Also, an enumerated type is supplied via its Class object, along with the type of the Map's values (in this case, simple strings). The output of this method is shown in Listing 11:
Listing 11. Output of Listing 10 [echo] Running AntStatusTester...Enum's Class object?You may have noticed that the sample code in Listing 10 actually implies Tiger treats enums as classes, which is evidenced by the AntStatusClass object being not only available, but also in use. This is true. Under the hood, Tiger views enums as a special class type. For more information on the implementation details of enums, see Chapter 3 of Java 5.0 Tiger: A Developer's Notebook (see Resources). Tutorial Pages: » Represent Constants in a Typesafe Manner Using Java 5.0 » Defining an Enum » Working with Enumerated Values » Enums and Collections » Going Further » Use Them, But Don't Abuse Them » Resources First published by IBM developerWorks |
|