2

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?

ceving
  • 21,900
  • 13
  • 104
  • 178

4 Answers4

6

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

Reference:

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • You could argue it does use hashing and that hash is the (unique) enum `ordinal()` ;) – Mark Rotteveel Jun 07 '13 at 09:48
  • Since when was a simply indexed array a hash table? It would only be a hash table if there was a non-trivial hash function that turned the `enum` value into a hash value. – Stephen C Jun 07 '13 at 09:50
  • I'm not entirely serious, but in the context of a 'perfect hash function' as mentioned in the question and the fact that you can look at `ordinal()` as being that perfect hash function, then it is not a big leap to consider the indexed array access as a hash table. – Mark Rotteveel Jun 07 '13 at 09:53
  • And FWIW, `Enum.hashcode()` does not return the ordinal. It just calls `super.hashcode()`. Yes, I suppose that you could say that a perfect hash table does behave like a (typically sparse) array *after* you have hashed the key. – Stephen C Jun 07 '13 at 09:55
  • Interesting, I did not know that. Could that mean that theoretically the `Enum.hashcode()` could have collisions, while `Enum.ordinal()` cannot? – Mark Rotteveel Jun 07 '13 at 09:59
3

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.

rli
  • 1,745
  • 1
  • 14
  • 25
3

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!

Sazzadur Rahaman
  • 6,938
  • 1
  • 30
  • 52
1

EnumMap are not hash based, they are based on arrays

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

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275