Question

If the list of hash keys for a hash function is known and immutable, it is possible to generate a perfect hash function. A Enum in Java is a list of known and immutable elements. Therefor it should be possible to implement the EnumMap as a perfect hash. Is this currently (1.7) done in Java?

Was it helpful?

Solution

No. EnumMap doesn't use hashing. It uses the enum ordinal values as indexes into an array of the value type.

Reference:

OTHER TIPS

The link you name "EnumHashMap" actually points to a class named "EnumMap", there are no hashes involved there:

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

For the sake of argument, one could argue that the mapping of enum - values to integer (as index into the abovementioned array) IS a hash function and yes, it is perfect, as there are no colissions.

EnumMap is not any kind of HashMap that would use hashing internally to put and get data. It uses Array to store the <K, V> pair where K is an Enumeration constant and uses ordinal value (the position of the Enumeration constant in the declaring Enum, is known as ordinal value) internally to put or get data. Enum.ordinal method is used for getting ordinal value of a given Enumeration constant.

In other words, EnumMap does not use hashing but ordinal values of the Enumeration constant as the index to put or get the <K, V> pair in its internal array.

You can check the source code of EnumMap.put for being over sure!

EnumMap are not hash based, they are based on arrays

private transient K[] keyUniverse; ... private transient Object[] vals;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top