Why use EnumMap instead of HashMap
Asked Answered
S

2

36

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

Sides answered 21/11, 2018 at 6:49 Comment(2)
did you read the docs?Strikebound
As the doc says This representation is extremely compact and efficient.Portillo
C
32

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.

Coniah answered 21/11, 2018 at 6:53 Comment(2)
Pretty much what I was copying :) I suggest OP looks into the source for EnumMap in order to see the shortcuts that can be taken when the entire "usage space" is known in advance (since enums are constant.)Sauls
There are also third-party libraries with similar specialized implementations of Map (and other types of Collections) for constrained key or value types such as int, all for the purpose of efficiency.Coniah
J
20

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);
Junction answered 21/11, 2018 at 6:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.