Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use EnumMap instead of HashMap

Tags:

As we already have HashMap, why would we use EnumMap?

like image 991
Ashish Choudhary Avatar asked Nov 21 '18 06:11

Ashish Choudhary


People also ask

What is the use of EnumMap in Java?

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 constants are declared inside enum type ) It's a high-performance map implementation, much faster than HashMap.

What is the best alternative for HashMap in Java?

Whereas, ConcurrentHashMap is introduced as an alternative to the HashMap. The ConcurrentHashMap is a synchronized collection class. The HashMap is non-thread-safe and can not be used in a Concurrent multi-threaded environment.

Can we use enum as key in HashMap?

In HashMap, there is no constraint. You can use Enum as well as any other Object as key.

Why are Hashmaps better than ArrayList?

While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively. ArrayList allows duplicate elements while HashMap doesn't allow duplicate keys but does allow duplicate values.


2 Answers

The Javadoc makes a pretty good argument:

Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

Implementation note: All basic operations execute in constant time. They are likely (though not guaranteed) to be faster than their HashMap counterparts.

like image 79
Thilo Avatar answered Sep 25 '22 21:09

Thilo


The main reason for EnumMap is that it is specifically optimised for enums. Further benefits are mentioned below.

Taken help from https://javarevisited.blogspot.com/2012/09/difference-between-enummap-and-hashmap-in-java-vs.html#axzz5XTB1xBUe

1) First and foremost difference between EnumMap and HashMap is that EnumMap is optimized for enum keys while HashMap is a general purpose Map implementation similar to Hashtable. you can not use any type other than Enum as key in EnumMap but you can use both Enum and any other Object as key in HashMap.

2) Another difference between EnumMap and HashMap is performance. as discussed in the previous point, due to specialized optimization done for Enum keys, EnumMap is likely to perform better than HashMap when using enum as key object.

3) One more thing which can be considered as the difference between HashMap and EnumMap is the probability of Collision. Since Enum is internally maintained as array and they are stored in their 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); 
like image 44
Pooja Aggarwal Avatar answered Sep 24 '22 21:09

Pooja Aggarwal