In JDK 1.5, there's a new collection class called EnumMap. As its name suggested, this map is a specialized map that designed specifically for enum. This seems to be a very little known class. At least I haven't seen it being used in any of the 1.5 codebases that I had been worked with over the last 2-3 years. I have, however, seen many many times where HashMap was used instead to store a collection of {enum -> value} mappings.

I didn't study the implementation of EnumMap, but I can imagine that it's using enum.ordinal() to index the element so it's probably faster than indexing using hashcode as in HashMap. Further, different from HashMap, the elements iteration order is maintained to be the natural order of the enum constants. This is often useful because chances are you will want to print the map. Having a controllable order will make the output more reader.

In short, EnumMap is in many way a better map data structure than HashMap if the keys are enum constants.


enum ABC{ A, B, C}
Map = new EnumMap(ABC.class);
//is better than
Map = new HashMap();