Search code examples
javadictionaryenumssparse-matrix

Sparse Map with Enum keys


I need to create a Map with enum keys where only a small fraction of the enum constants will be actually inserted. What is the best approach? An EnumMap would be inefficient if the length of its underlying array is equal to the total number of enum constants.


Solution

  • I suggest using an ordinary HashMap.

    Computing hashes for enums is both easy and cheap. There should be no significant memory overhead, since you are not duplicating the enum objects, but instead creating multiple references to the same object. For this reason, there should be little difference between storing an integer key and storing a reference to an enum object.