I recently read an article about EnumMap
. It's written that "using EnumMap brings implementation specific benefits which is done for enum keys, In short EnumMap
is optimized Map implementation exclusively for enum keys."
It's also written that "Enum is implemented using Arrays and common operations result in constant time. So if you are thinking of an high performance Map
, EnumMap
could be decent choice for enumeration data."
Looking at the documentation for EnumMap:
A specialized
Map
implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.Enum maps are maintained in the natural order of their keys (the order in which the enum constants are declared). This is reflected in the iterators returned by the collections views (
keySet()
,entrySet()
, andvalues()
).
In short, an EnumMap
is just an array, of the type of the values of the map. In other words, an EnumMap<SomeEnum, SomeValue>
, would be just a SomeValue[]
.
How are the indexes assigned, you might ask? They are assigned by the natural order of the enum. Example:
enum Day {
MON, TUE, WED, THU, FRI, SAT, SUN
}
The above enum has the following natural order.
MON TUE WED THU FRI SAT SUN
0 1 2 3 4 5 6
So, an operation like map.put(Day.FRI, "Yay!")
can actually be viewed as:
array[4] = "Yay!";
Array access is a constant time operation, and that's why the EnumMap
benefits of it as well. The look up (get()
) works just the same way.
As you can see from the source, an EnumMap
contains an array of objects of length exactly the number of values in the enum
. For (for instance) put
and get
, the ordinal value of the enum
value is used as array index. This operation obviously takes constant time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With