简体   繁体   中英

How to efficiently use Enum objects as keys in the Map data structure?

是否有更高效和专业的Map集合实现,其中Enum对象可以作为键?

Yes. EnumMap is precisely that; an efficient implementation of the Map interface, in which the key type must be an enum:

From the API documentation :

Class EnumMap<K extends Enum<K>,V>

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

Example usage:

Map<MyEnum, String> map = new EnumMap<MyEnum, String>(MyEnum.class);

BTW, it's simpler to write:

Map<MyEnum, String> map = new EnumMap<>(MyEnum.class);

There's no need to repeat the types. This can make the code a lot easier to read.

I learned this recently after I accidentally stumbled upon the answer in the Java API. If you ever have a map that uses enums as keys make sure you use EnumMap . It's very simple and much more efficient:

public interface LibraryItem{ ... }

public enum LibraryItemType{ BOOK, CD, VHS, AUDIO; ... }

Map<LibraryItemType, NavigableSet<LibraryItem>> itemsByType =
    new EnumMap<>(LibraryItemType.class);

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