What is EnumMap ?

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.
Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared). This is reflected in the iterators returned by the collections views (keySet(), entrySet(), and values()).
Null keys are not permitted. Attempts to insert a null key will throw NullPointerException.Attempts to test for the presence of a null key or to remove one will, however, function properly. Null values are permitted.
Ex:
import java.io.IOException;
import java.io.PrintStream;
import java.util.EnumMap;

enum myEnum {
INITIALIZING,
COMPILING,
COPYING,
JARRING,
ZIPPING,
DONE,
ERROR
}
public class demo {

public demo() { }

public void testEnumMap(PrintStream out) throws IOException {
// Create a map with the key and a String message
EnumMap messages =
new EnumMap(myEnum.class);

// Initialize the map
messages.put(myEnum.INITIALIZING, "Initializing...");
messages.put(myEnum.COMPILING, "Compiling Java classes...");
messages.put(myEnum.COPYING, "Copying files...");
messages.put(myEnum.JARRING, "JARring up files...");
messages.put(myEnum.ZIPPING, "ZIPping up files...");
messages.put(myEnum.DONE, "Build complete.");
messages.put(myEnum.ERROR, "Error occurred.");

// Iterate and print messages
for (myEnum status : myEnum.values() ) {
out.println("For status " + status + ", message is: " +
messages.get(status));
}
}

public static void main(String[] args) {
try {
demo tester = new demo();

tester.testEnumMap(System.out);
} catch (IOException e) {
e.printStackTrace();
}
}
}

No comments:

Post a Comment