Getting Started with Enumerated Types
By Brett McLaughlin2005-04-22
Enums and Collections
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:
public enum AntStatus {
INITIALIZING,
COMPILING,
COPYING,
JARRING,
ZIPPING,
DONE,
ERROR
}
Listing 10. Maps of enums
public void testEnumMap(PrintStream out) throws IOException {
// Create a map with the key and a String message
EnumMap<AntStatus, String> antMessages =
new EnumMap<AntStatus, String>(AntStatus.class);
// Initialize the map
antMessages.put(AntStatus.INITIALIZING, "Initializing Ant...");
antMessages.put(AntStatus.COMPILING, "Compiling Java classes...");
antMessages.put(AntStatus.COPYING, "Copying files...");
antMessages.put(AntStatus.JARRING, "JARring up files...");
antMessages.put(AntStatus.ZIPPING, "ZIPping up files...");
antMessages.put(AntStatus.DONE, "Build complete.");
antMessages.put(AntStatus.ERROR, "Error occurred.");
// Iterate and print messages
for (AntStatus status : AntStatus.values() ) {
out.println("For status " + status + ", message is: " +
antMessages.get(status));
}
}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).
[java] For status INITIALIZING, message is: Initializing Ant...
[java] For status COMPILING, message is: Compiling Java classes...
[java] For status COPYING, message is: Copying files...
[java] For status JARRING, message is: JARring up files...
[java] For status ZIPPING, message is: ZIPping up files...
[java] For status DONE, message is: Build complete.
[java] For status ERROR, message is: Error occurred.
Tutorial pages:
|
First published by IBM developerWorks
|
|||||||||
You might also want to check these out:
|
Leave a Comment on "Getting Started with Enumerated Types"
You must be logged in to post a comment.
Link to This Tutorial Page!

