Difference Between EnumMap and HashMap
EnumMap and HashMap both are the classes that implement the Map interface. But there are some differences that exist between them. So we have tried to list out the differences between EnumMap and HashMap.
1. EnumMap: EnumMap is a specialized implementation of the Map interface for enumeration types. It extends AbstractMap and implements the Map interface in Java. Few important points of EnumMap are as follows:
- EnumMap class is a member of the Java Collections Framework and it is not synchronized.
- EnumMap is an ordered collection, and they are maintained in the natural order of their keys(the natural order of keys means the order on which enum constant are declared inside enum type).
- EnumMap is much faster than HashMap.
- All keys of each EnumMap instance must be keys of the same enum type.
- EnumMap doesn’t allow inserting null key if we try to insert the null key, it will throw NullPointerException.
- EnumMap is internally represented as arrays therefore it gives the better performance.
Size of EnumMap: 4 Sunday 1 Monday 2 Tuesday 3 Wednesday 4
2. HashMap: HashMap is a class that implements the Map interface. It stores the data in the key and value pair, where the key should be unique. If you try to insert the duplicate key, it will replace the element of the corresponding key. It allows to store the null keys as well as null values, but there should be only one null key and multiple null values. Java HashMap is similar to HashTable, but it is synchronized. HashMap doesn’t maintain the order that means it doesn’t guarantee any specific order of the elements.
Size of map is: 3 20 Ram 10 Geeks 30 Shyam
Difference between EnumMap and HashMap
|EnumMap is a specialized map implementation that uses only Enum type key.||In HashMap, we can use Enum as well as any other object as a key.|
|It doesn’t allow storing null key.||It allows to store the null keys as well values, but there should be only one null key object and there can be any number of null values.|
|EnumMap internally uses the array||HashMap internally uses the HashTable.|
|EnumMap is a specialized map implementation that uses only enum type keys. Due to this, EnumMap is performed better than HashMap.||Performance of HashMap is slightly less than compared to EnumMap.|
|EnumMap stores the keys in the natural order of their keys (order in which the enum constant are declared).||In HashMap, no ordering of the keys.|
|Since EnumMap internally uses the array and stores the key in their natural ordering using ordinal(), so there is no probability of collision.||HashMap uses the hashCode() to store key and values, so there is probability of collision.|
Please Login to comment...