简体   繁体   中英

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.

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.

I'd also go with either a HashMap or a TreeMap (depending on whether you need a deterministic Iterator or not). Since your data is sparse, any real or imagined overhead is unlikely to be a significant performance hurdle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM