Difference between EnumMap and HashMap in Java - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Sunday, March 12, 2017

Difference between EnumMap and HashMap in Java

EnumMap vs HashMap in Java

What is the difference between HashMap and EnumMap in java is the tricky interview question if you are not familiar with EnumMap in Java. EnumMap is not popular as HashMap, EnumMap can use with only enum type keys. The main difference between EnumMap and HashMap is that EnumMap is the specialized implementation of Map interface for use with enum type keys, introduced in Java 1.5 with enumeration type. Using Enum as key allows doing some optimization on Map which is usually not possible with the other object key.

HashMap extends AbstractMap and implement Map interface, EnumMap extends AbstractMap class. AbstractMap class implements Map interface. So both EnumMap and HashMap are implementation of Map interface. Both can access the method of Map interface ( like put, and get). EnumMap internally using as arrays, this representation is extremely compact and efficient. On other hand, HashMap internally uses HashTable.

Let's see the difference between EnumMap and HashMap.

EnumMap HashMap
EnumMap is optimized for Enum type keys to store in map. EnumMap internally using as arrays, this representation is extremely compact and efficient, provide constant time performance for common methods like get, and put. HashMap is general purpose map implementation, internally uses HashTable. HashMap can use any object as key.
Due to specialized optimization done in EnumMap, its performance is better than HashMap. HashMap performance is not better as EnumMap.
Only Enum type can use as keys in EnumMap. All type of object can use as keys in HashMap.
Since EnumMap internally maintain an array and they are stored in their natural order using ordinal(), so there is no probability of collision. HashMap using hashCode() to store the keys and values so there is probability of collision.
EnumMap stores keys in the natural order of their keys (the order in which the enum constants are declared). HashMap is not ordered, HashMap order can change over the time.

No comments :

Post a Comment