EnumMap or HashMap if lookup key is a String

后端 未结 4 1864
花落未央
花落未央 2021-02-03 21:45

I\'m trying to weigh the pros and cons of using an EnumMap over a HashMap. Since, I will always be looking up using a String, it seems tha

4条回答
  •  终归单人心
    2021-02-03 22:46

    If the set of possible keys is finite and known in advance (as your example/question suggest), then the enum is a perfect representation of this. As other said, the use of an enum ensures that no mistake will be made in the use of the key.

    Furthermore, this implementation of Map is quite optimized, as the range of the keys is known in advance (as far as I knwow, the EnumMap uses an array of length numberOfEnums internally, indexed by the enum's ordinal).

    So I would also recommend EnumMap.

    Two (little) things to keep in mind though :

    • you won't be able to add specialized cases by inheritance (you cannot extend an enum, so no Maps of ANIMALS with specialized Maps of MAMMALS on the side for example)
    • when adding a member to your enum, if you add it "in the middle" of the other members you change the ordinals. As this info can be used by the EnumMap, this can prove problematic if you reload an EnumMap constructed from the old version of the enum (for example using Serialization)

提交回复
热议问题