Monday, March 25, 2013

Difference between EnumMap and HashMap in Java

 
S No
EnumMap
HashMap
1
EnumMap is optimized for enum keys
HashMap is a general purpose Map implementation similar to Hashtable



2
you can not use any type other than Enum as key in EnumMap




you can use both Enum and any other Object as key in HashMap




3
Due to specialized optimization done for Enum keys, EnumMap is likely to perform better than HashMap when using enum as key object



-
4
Since Enum is internally maintain as array and they are stored in there natural order using ordinal(), as shown in following code which is taken from put() method of EnumMap

    int index = ((Enum)key).ordinal();
    Object oldValue = vals[index];
    vals[index] = maskNull(value);



-

These were some notable difference between EnumMap and HashMap in Java. In short EnumMap is best suited for enum keys, for which it has optimized and perform better than HashMap in Java. Use EnumMap whenever you can use enum as keys.

No comments:

Post a Comment